package com.corpgovernment.organization.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.corpgovernment.api.applytrip.enums.ApplyTripEmployeeEnum;
import com.corpgovernment.api.fpcard.dto.FrequencyVo;
import com.corpgovernment.api.fpcard.dto.FrequentPassengerDto;
import com.corpgovernment.api.fpcard.soa.FpCardApiClient;
import com.corpgovernment.api.organization.bo.*;
import com.corpgovernment.api.organization.enums.CardTypeEnum;
import com.corpgovernment.api.organization.enums.UserOrgRelationStatusEnum;
import com.corpgovernment.api.organization.model.base.PageInfoResponse;
import com.corpgovernment.api.organization.model.bookingrelation.BookingRange;
import com.corpgovernment.api.organization.model.ffpinfo.GetFfBasicsInfoResponse;
import com.corpgovernment.api.organization.model.org.CorpNode;
import com.corpgovernment.api.organization.model.org.GetOrgTreeResponse;
import com.corpgovernment.api.organization.model.org.ListOrgTreeByConditionResponse;
import com.corpgovernment.api.organization.model.org.OrgInfoVo;
import com.corpgovernment.api.organization.model.org.base.ContactInfoVo;
import com.corpgovernment.api.organization.model.org.base.ExpressAddressVo;
import com.corpgovernment.api.organization.model.org.base.InvoiceInfoVo;
import com.corpgovernment.api.organization.model.org.base.LandmarkVO;
import com.corpgovernment.api.organization.model.org.front.*;
import com.corpgovernment.api.organization.model.org.queryorgparentcompany.OrgAndParentCompanyInfoDTO;
import com.corpgovernment.api.organization.model.org.queryorgparentcompany.QueryOrgParentCompanyRequest;
import com.corpgovernment.api.organization.model.org.queryorgparentcompany.QueryOrgParentCompanyResponse;
import com.corpgovernment.api.organization.model.org.request.*;
import com.corpgovernment.api.organization.model.org.response.DeleteResponse;
import com.corpgovernment.api.organization.model.org.response.GetOrgInfoResponseNew;
import com.corpgovernment.api.organization.model.org.response.RegisterCorpResponse;
import com.corpgovernment.api.organization.model.passenger.CardVo;
import com.corpgovernment.api.organization.model.passenger.MobilePhoneVo;
import com.corpgovernment.api.organization.model.settlement.OrgInfoWithPermission;
import com.corpgovernment.api.organization.model.settlement.QueryOrgInfoWithPermissionRequest;
import com.corpgovernment.api.organization.model.settlement.QueryOrgInfoWithPermissionResponse;
import com.corpgovernment.api.organization.model.user.NameInfoBo;
import com.corpgovernment.api.organization.model.user.employee.NameInfoVo;
import com.corpgovernment.api.organization.model.user.login.MbUserLoginVo;
import com.corpgovernment.api.organization.utils.CommonUtil;
import com.corpgovernment.api.organization.utils.RegularUtils;
import com.corpgovernment.api.organization.vo.GetOrgTreeReq;
import com.corpgovernment.api.organization.vo.GetOrgTreeRsp;
import com.corpgovernment.api.organization.vo.TransferEmployeeOrgInfoVo;
import com.corpgovernment.common.apollo.OrganizationApollo;
import com.corpgovernment.common.base.BaseUserInfo;
import com.corpgovernment.common.base.CommonException;
import com.corpgovernment.common.base.JSONResult;
import com.corpgovernment.common.base.ResourceInfo;
import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.common.dto.UserCardValidationInfoReqVo;
import com.corpgovernment.common.enums.CardEnum;
import com.corpgovernment.common.enums.ExceptionCodeEnum;
import com.corpgovernment.common.enums.ResourceEnum;
import com.corpgovernment.common.handler.ICacheHandler;
import com.corpgovernment.common.utils.*;
import com.corpgovernment.common.utils.DataPermissions.DataPermissionsContext;
import com.corpgovernment.costcenter.service.impl.CostCenterServiceImpl;
import com.corpgovernment.job.service.JobService;
import com.corpgovernment.organization.constant.*;
import com.corpgovernment.organization.convert.LandmarkConvert;
import com.corpgovernment.organization.convert.UserCardInfoConvert;
import com.corpgovernment.organization.dataloader.ApplyTripClientLoader;
import com.corpgovernment.organization.dataloader.ApprovalClientLoader;
import com.corpgovernment.organization.dataloader.db.*;
import com.corpgovernment.organization.dto.ListEmployeeQuery;
import com.corpgovernment.organization.dto.MbFreshPassengerRelationDTO;
import com.corpgovernment.organization.dto.MbOrgEmployeeInfoDto;
import com.corpgovernment.organization.entity.db.*;
import com.corpgovernment.organization.enumm.CardCodeEnum;
import com.corpgovernment.organization.enumm.DeviceEnum;
import com.corpgovernment.organization.enumm.OrgTypeEnum;
import com.corpgovernment.organization.mapper.MbFreshPassengerRelationMapper;
import com.corpgovernment.organization.mapper.MbOrgInfoMapper;
import com.corpgovernment.organization.mapper.MbOrgNonEmployeeMapper;
import com.corpgovernment.organization.mapper.MbOrgUserIdcardMapper;
import com.corpgovernment.organization.model.*;
import com.corpgovernment.organization.model.FfpAddRequest.CardInfo;
import com.corpgovernment.organization.model.org.dto.OrgInfoAllDto;
import com.corpgovernment.organization.operatelog.service.pojo.OrgInfoPojo;
import com.corpgovernment.organization.service.*;
import com.corpgovernment.organization.util.CardTypeSwitchUtil;
import com.corpgovernment.organization.util.OrganizationUtil;
import com.corpgovernment.organization.util.StrUtils;
import com.corpgovernment.organization.vo.FfpPageVo;
import com.corpgovernment.organization.vo.GetOrgTreeRequest;
import com.corpgovernment.organization.vo.ListEmployeeInOrgVO;
import com.corpgovernment.organization.vo.SearchCorpEmpResponse;
import com.corpgovernment.permission.service.MbRoleResourceService;
import com.corpgovernment.permission.service.RoleResourceService;
import com.corpgovernment.permission.vo.UpdateFfpResultVo;
import com.corpgovernment.redis.cache.RoleResourceManager;
import com.corpgovernment.redis.cache.UserCacheManager;
import com.corpgovernment.supplier.dto.SupplierCompanyDto;
import com.corpgovernment.supplier.service.SupplierCompanyService;
import com.ctrip.corp.obt.generic.core.context.UserInfoContext;
import com.ctrip.corp.obt.generic.event.core.EventCenter;
import com.ctrip.corp.obt.generic.security.utils.DesensitizationUtils;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.ctrip.corp.obt.shard.context.PageContext;
import com.ctrip.corp.obt.shard.sql.mybatis.interceptor.pagination.IPage;
import com.ctrip.corp.obt.shard.sql.mybatis.interceptor.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import tk.mybatis.mapper.entity.Example;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.Map.Entry;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.corpgovernment.common.utils.DateUtil.DF_YMD_HMS;

/**
 * 组织信息服务
 *
 * @author qkdong
 */
@Service
@Slf4j
public class OrganizationInfoServiceImpl extends OrganizationBaseService implements IOrganizationInfoService {

    @Autowired
    private MbOrgInfoMapper mbOrgInfoMapper;
    @Autowired
    private IFreshPassengerService freshPassengerService;
    @Autowired
    private IOrgUserIdCardService organizationUserIdCardService;
    @Autowired
    private MbOrgNonEmployeeMapper mbOrgNonEmployeeMapper;
    @Autowired
    private FpCardApiClient fpCardApiService;
    @Autowired
    private IUserOrgRelationService userOrgRelationService;
    @Autowired
    private FreshPassengerRelationServiceImpl freshPassengerRelationService;
    @Autowired
    private UserCardInfoConvert userCardInfoConvert;
    @Autowired
    private BookingRelationService bookingRelationService;
    @Autowired
    private CommonInvoiceInfoService commonInvoiceInfoService;
    @Autowired
    private ICacheHandler iCacheHandler;
    @Autowired
    private ExpressAddressServiceImpl expressAddressService;
    @Autowired
    private IOrgPayTypeService orgPayTypeService;
    @Autowired
    private IOrganizationEmployeeService organizationEmployeeService;
    @Autowired
    private IOrganizationUserFfpService organizationUserFfpService;
    @Autowired
    private IUserLoginService userLoginService;
    @Autowired
    private IPostService postService;
    @Autowired
    private CostCenterServiceImpl costCenterService;
    @Autowired
    private LandmarkConvert landmarkConvert;
    @Autowired
    private LandmarkLoader landmarkLoader;
    @Autowired
    private MbFreshPassengerRelationMapper mbFreshPassengerRelationMapper;
    @Autowired
    private MbOrgUserIdcardMapper mbOrgUserIdcardMapper;
    @Autowired
    private MbOrgEmployeeLoader mbOrgEmployeeLoader;
    @Autowired
    private RoleResourceService roleResourceService;
    @Autowired
    private MbRoleResourceService mbRoleResourceService;
    @Autowired
    private IOrganizationInfoService organizationInfoService;
    @Autowired
    private ApprovalClientLoader approvalClientLoader;
    @Autowired
    private MbUserRoleLoader userRoleLoader;
    @Autowired
    private RoleResourceManager manager;
    @Autowired
    private IOrgConfigService orgConfigService;
    @Autowired
    private EventCenter eventCenter;
    @Autowired
    private OrganizationChangeHistoryLoader organizationChangeHistoryLoader;
    @Autowired
    private ApplyTripClientLoader applyTripClientLoader;

    @Autowired
    private UserCacheManager userCacheManager;

    @Autowired
    private MbOrgNonEmployeeLoader mbOrgNonEmployeeLoader;

    @Autowired
    private SupplierCompanyService supplierCompanyService;
    @Autowired
    private JobService jobService;

    @Autowired
    private OrganizationApollo organizationApollo;

    @Autowired
    private MbUserOrgRelationLoader mbUserOrgRelationLoader;

    private static final int RECURSION_TIMES = 50;
    private static final String NAME_MATCH_WARN = "2222";
    private static final String PORTAL_SOURCE = "SUPPLIER";

    @Override
	@Transactional
	public JSONResult updateOrgInfo(UpdateOrgRequest request) {
		log.info("参数saveOrUpdateOrgInfo:{}", JsonUtils.toJsonString(request));
        // 清除字符串空格
        //ObjectStringTrimUtils.allFieldRemoveWarp(request);

        //1.联系信息
		ContactInfoVo contactInfo = request.getContactInfo();
		MbOrgInfo mbOrgInfo = new MbOrgInfo();
		mbOrgInfo.setOrgId(contactInfo.getOrgId());
		mbOrgInfo.setContactName(contactInfo.getContactName());
		mbOrgInfo.setContactPhone(contactInfo.getContactPhone());
        mbOrgInfo.setContactAreaCode(contactInfo.getAreaCode());
        mbOrgInfo.setContactEmail(contactInfo.getContactEmail());
        updateContactInfo(mbOrgInfo);
        List<MbOrgInfo> orgInfoList = mbOrgInfoMapper.listByOrgIdsWithoutBackground(Lists.newArrayList(contactInfo.getOrgId()));
        String orgId = contactInfo.getOrgId();
        MbOrgInfo orgInfo = orgInfoList.iterator().next();
        //2.发票信息
        //有发票信息并且为公司才操作
        if (!CollectionUtils.isEmpty(request.getInvoiceInfoList()) && Objects.equals(OrgTypeEnum.C.getCode(), orgInfo.getOrgType())) {
            List<MbCommonInvoiceInfo> mbCommonInvoiceInfoList = CommonUtil.copyList(request.getInvoiceInfoList(), MbCommonInvoiceInfo.class);
            log.info("mbCommonInvoiceInfoList:{}", JsonUtils.toJsonString(mbCommonInvoiceInfoList));
            mbCommonInvoiceInfoList.forEach(i -> i.setOrgId(orgId));

            commonInvoiceInfoService.addOrUpdateCommonInvoiceInfo(mbCommonInvoiceInfoList);
        }

        //3.配送地址信息
        if (!CollectionUtils.isEmpty(request.getExpressAddressList())) {
            List<MbExpressAddress> mbExpressAddressList = CommonUtil.copyList(request.getExpressAddressList(), MbExpressAddress.class);
            log.info("mbExpressAddressList:{}", JsonUtils.toJsonString(mbExpressAddressList));

            List<MbExpressAddress> insertList = mbExpressAddressList.stream().filter(bean -> {
                bean.setOrgId(orgId);
                bean.setIsCorporation(false);
                return null == bean.getId() || bean.getId() == 0;
            }).collect(Collectors.toList());
            log.info("mbExpressAddressList insertList:{}", JsonUtils.toJsonString(insertList));
            if (CollectionUtils.isNotEmpty(insertList)) {
                expressAddressService.insertBatch(insertList);
            }

            List<MbExpressAddress> updateList = mbExpressAddressList.stream().filter(bean -> {
                bean.setIsCorporation(false);
                return null != bean.getId() && bean.getId() > 0;
            }).collect(Collectors.toList());
            log.info("mbCommonInvoiceInfoList update:{}", JsonUtils.toJsonString(updateList));
            if (CollectionUtils.isNotEmpty(updateList)) {
                expressAddressService.updateBatch(mbExpressAddressList);
            }
        }
        // 4.处理地标信息
        processLandmarkInfo(request.getLandmarkList(), request.getOrgId());
        return JSONResult.ok();
    }

    /**
     * 处理组织地标信息
     *
     * @param landmarkList
     */
    private void processLandmarkInfo(List<LandmarkVO> landmarkList, String orgId) {
        List<MbLandmark> mbLandmarkList = landmarkConvert.convertFromVo(landmarkList);
        List<MbLandmark> mbLandmarkListNew = new ArrayList<>();
        //查询部门所属公司
        MbOrgInfo corpOrgInfo = this.findRecentCompanyIdByOrgId(orgId);
        //自己本身就是公司
        if (orgId.equals(corpOrgInfo.getOrgId())){
            //将公司下所有部门地标更新一遍
            //查询公司下所有部门 不穿透子公司
            List<String> orgIds = this.listAllDepartmentIds(corpOrgInfo.getOrgId(), false);
            orgIds.add(orgId);
            log.info("处理组织地标信息1:{}", JsonUtils.toJsonString(orgIds));
            if (CollectionUtils.isNotEmpty(mbLandmarkList)) {

                //复制一遍数据给部门
                for (String str:orgIds){
                    mbLandmarkList.forEach(item ->{
                        MbLandmark mbLandmarkNew = new MbLandmark();
                        BeanUtils.copyProperties(item, mbLandmarkNew);
                        mbLandmarkNew.setOrgId(str);
                        mbLandmarkListNew.add(mbLandmarkNew);
                    });
                }
                //数据量不大可以先删后增
                landmarkLoader.delByOrgId(orgIds);
                mbLandmarkListNew.forEach(item ->item.setId(null));
                log.info("处理组织地标信息2:{}", JsonUtils.toJsonString(mbLandmarkListNew));
                landmarkLoader.insertBatchNew(mbLandmarkListNew);
            } else {
                //如果前端不传 则全部删除
                landmarkLoader.delByOrgId(orgIds);
            }

        } else {
          //部门不让改地标也
        }

//        //是否新增
//		List<MbLandmark> insertList = mbLandmarkList.stream().filter(e -> e.getId() == null || e.getId() == 0).collect(Collectors.toList());
//		if (CollectionUtils.isNotEmpty(insertList)) {
//			landmarkLoader.insertBatch(insertList);
//		}
//		//原有数据进行修改
//		List<MbLandmark> updateList = mbLandmarkList.stream().filter(e -> e.getId() != null && e.getId() > 0).collect(Collectors.toList());
//		if (CollectionUtils.isNotEmpty(updateList)) {
//			landmarkLoader.updateBatch(updateList);
//		}
//        //是否删除
//        List<MbLandmark> mbLandmarks = landmarkLoader.listByOrgId(orgId);
//        if (CollectionUtils.isNotEmpty(mbLandmarks)) {
//            Set<Long> collect = updateList.stream().map(MbLandmark::getId).collect(Collectors.toSet());
//            List<MbLandmark> delData = mbLandmarks.stream().filter(a -> !collect.contains(a.getId())).collect(Collectors.toList());
//            if (CollectionUtils.isNotEmpty(delData)) {
//                landmarkLoader.del(delData.stream().map(MbLandmark::getId).collect(Collectors.toList()));
//            }
//
//        }
    }

    @Override
    public JSONResult<GetOrgInfoResponseNew> getOrgInfo(GetOrgInfoRequest request) {

        log.info("getOrgInfo入参:{}", JsonUtils.toJsonString(request));
        String orgId = request.getOrgId();
        GetOrgInfoResponseNew getOrgInfoResponse = getOrgInfoByOrgId(orgId);
        //        GetOrgInfoResponseNew getOrgInfoResponse = mbOrgInfoMapper.selectByOrgId(request.getOrgId());
        log.info("getOrgInfoResponse结果:{}", JsonUtils.toJsonString(getOrgInfoResponse));
        return JSONResult.success(getOrgInfoResponse);
    }

    public OrgInfoPojo convertOrgInfo(GetOrgInfoRequest request) {
        OrgInfoPojo orgInfoPojo = null;
        GetOrgInfoResponseNew getOrgInfoResponse = getOrgInfoByOrgId(request.getOrgId());
        if (getOrgInfoResponse != null) {
            ContactInfoVo contactInfo = getOrgInfoResponse.getContactInfo();
            orgInfoPojo = new OrgInfoPojo();
            //联系信息
            orgInfoPojo.setContactName(contactInfo.getContactName());
            orgInfoPojo.setContactPhone(contactInfo.getAreaCode() + " " + contactInfo.getContactPhone());
            orgInfoPojo.setContactEmail(contactInfo.getContactEmail());

            //发票信息
            List<InvoiceInfoVo> invoiceInfoList = getOrgInfoResponse.getInvoiceInfoList();
            if (CollectionUtils.isNotEmpty(invoiceInfoList)) {
                List<String> invoiceList = invoiceInfoList.stream().map(InvoiceInfoVo::getInvoiceTitle).collect(Collectors.toList());
                orgInfoPojo.setInvoiceTitle(StringUtils.join(invoiceList, ","));
                List<String> TaxIdList = invoiceInfoList.stream().map(InvoiceInfoVo::getTaxId).collect(Collectors.toList());
                orgInfoPojo.setTaxId(StringUtils.join(TaxIdList, ","));
                List<String> accountBankList = invoiceInfoList.stream().map(InvoiceInfoVo::getAccountBank).collect(Collectors.toList());
                orgInfoPojo.setAccountBank(StringUtils.join(accountBankList, ","));
                List<String> accountCardNoList = invoiceInfoList.stream().map(InvoiceInfoVo::getAccountCardNo).collect(Collectors.toList());
                orgInfoPojo.setAccountCardNo(StringUtils.join(accountCardNoList, ","));
                List<String> corporationPhoneList = invoiceInfoList.stream().map(InvoiceInfoVo::getCorporationPhone).collect(Collectors.toList());
                orgInfoPojo.setCorporationPhone(StringUtils.join(corporationPhoneList, ","));
                List<String> aorporationAddressList = invoiceInfoList.stream().map(InvoiceInfoVo::getCorporationAddress).collect(Collectors.toList());
                orgInfoPojo.setCorporationAddress(StringUtils.join(aorporationAddressList, ","));
            }
            //配送地址
            List<ExpressAddressVo> expressAddressList = getOrgInfoResponse.getExpressAddressList();
            if (CollectionUtils.isNotEmpty(expressAddressList)) {
                List<String> addressList = expressAddressList.stream().map(ExpressAddressVo::getAddress).collect(Collectors.toList());
                orgInfoPojo.setAddress(StringUtils.join(addressList, ","));
                List<String> recipientNameList = expressAddressList.stream().map(ExpressAddressVo::getRecipientName).collect(Collectors.toList());
                orgInfoPojo.setRecipientName(StringUtils.join(recipientNameList, ","));
                StringBuffer recipientPhone = new StringBuffer();
                StringBuffer cityArea = new StringBuffer();
                for (ExpressAddressVo expressAddressVo : expressAddressList) {
                    recipientPhone.append(expressAddressVo.getCountryCode()).append(" ").append(expressAddressVo.getRecipientPhone()).append(",");
                    cityArea.append(expressAddressVo.getProvinceName()).append(expressAddressVo.getCityName()).append(expressAddressVo.getDistrictName()).append(",");
                }
                if (recipientPhone != null && recipientPhone.indexOf(",") != -1) {
                    recipientPhone = recipientPhone.deleteCharAt(recipientPhone.lastIndexOf(","));
                    orgInfoPojo.setRecipientPhone(String.valueOf(recipientPhone));
                }
                if (cityArea != null && cityArea.indexOf(",") != -1) {
                    cityArea = cityArea.deleteCharAt(cityArea.lastIndexOf(","));
                    orgInfoPojo.setCityArea(String.valueOf(cityArea));
                }
            }
        }
        return orgInfoPojo;
    }

    private GetOrgInfoResponseNew getOrgInfoByOrgId(String orgId) {
        GetOrgInfoResponseNew getOrgInfoResponse = new GetOrgInfoResponseNew();
        getOrgInfoResponse.setOrgId(orgId);

        MbOrgInfo orgInfo = findByOrgId(orgId);
        if (orgInfo != null) {
            ContactInfoVo contact = new ContactInfoVo();
            contact.setOrgId(orgId);
            contact.setContactName(orgInfo.getContactName());
            contact.setContactPhone(orgInfo.getContactPhone());
            contact.setAreaCode(orgInfo.getContactAreaCode());
            contact.setContactEmail(orgInfo.getContactEmail());
            getOrgInfoResponse.setContactInfo(contact);
            getOrgInfoResponse.setBusinessCode(orgInfo.getBusinessCode());
            List<MbCommonInvoiceInfo> listInvoice = commonInvoiceInfoService.listByOrgIdReal(orgId);
            getOrgInfoResponse.setInvoiceInfoList(CollectionUtils.isEmpty(listInvoice) ? new ArrayList<>() : listInvoice.stream().filter(Objects::nonNull).map(i -> {
                InvoiceInfoVo temp = new InvoiceInfoVo();
                temp.setId(i.getId());
                temp.setInvoiceTitle(i.getInvoiceTitle());
                temp.setTaxId(i.getTaxId());
                temp.setAccountBank(i.getAccountBank());
                temp.setAccountCardNo(i.getAccountCardNo());
                temp.setCorporationPhone(i.getCorporationPhone());
                temp.setCorporationAddress(i.getCorporationAddress());
                temp.setIsDeleted(i.getIsDeleted());
                return temp;
            }).collect(Collectors.toList()));

            List<MbExpressAddress> listAddress = expressAddressService.listByOrgId(orgId);
            if (OrgTypeEnum.D.getCode().equals(orgInfo.getOrgType()) && CollectionUtils.isEmpty(listAddress)) {
                MbOrgInfo corpOrgInfo = this.findRecentCompanyIdByOrgId(orgId);
                List<MbExpressAddress> mbExpressAddresses = expressAddressService.listByOrgId(corpOrgInfo.getOrgId());
                if (!CollectionUtils.isEmpty(mbExpressAddresses)){
                    mbExpressAddresses.forEach(item ->{
                        item.setId(null);
                        item.setOrgId(orgId);
                    });
                    expressAddressService.insertBatch(mbExpressAddresses);
                    listAddress = mbExpressAddresses;
                }
            }

            getOrgInfoResponse.setExpressAddressList(CollectionUtils.isEmpty(listAddress) ? new ArrayList<>() : listAddress.stream().filter(Objects::nonNull).map(a -> {
                ExpressAddressVo temp = new ExpressAddressVo();
                temp.setId(a.getId());
                temp.setDistrictName(a.getDistrictName());
                temp.setDistrict(a.getDistrict());
                temp.setCityName(a.getCityName());
                temp.setCity(a.getCity());
                temp.setProvinceName(a.getProvinceName());
                temp.setProvince(a.getProvince());
                temp.setAddress(a.getAddress());
                temp.setPostCode(a.getPostCode());
                temp.setRecipientName(a.getRecipientName());
                temp.setCountryCode(a.getCountryCode());
                temp.setRecipientPhone(a.getRecipientPhone());
                temp.setIsDefault(a.getIsDefault());
                temp.setIsDeleted(a.getIsDeleted());
                return temp;
            }).collect(Collectors.toList()));
            List<MbLandmark> landmarkList = landmarkLoader.listByOrgId(orgId);
            //如果查询得为部门 且 没有配置地标 自动补齐(上级公司没配置就算了)
            if (OrgTypeEnum.D.getCode().equals(orgInfo.getOrgType()) && CollectionUtils.isEmpty(landmarkList)) {
                //查询部门所属公司
                MbOrgInfo corpOrgInfo = this.findRecentCompanyIdByOrgId(orgId);
                List<MbLandmark> corpLandmarkList = landmarkLoader.listByOrgId(corpOrgInfo.getOrgId());
                if (!CollectionUtils.isEmpty(corpLandmarkList) && corpLandmarkList.size() > 0){
                    //给插入公司地标
                    corpLandmarkList.forEach(item ->{
                        item.setId(null);
                        item.setOrgId(orgId);
                    });
                    landmarkLoader.insertBatchNew(corpLandmarkList);
                    landmarkList = corpLandmarkList;
                }
            }
            List<LandmarkVO> landmarkVOS = landmarkConvert.convertToVo(landmarkList);
            getOrgInfoResponse.setLandmarkList(landmarkVOS);
        }
        return getOrgInfoResponse;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
    public DeleteResponse delete(DeleteRequest request, BaseUserInfo baseUserInfo) {
        log.info("delete入参:{}", JsonUtils.toJsonString(request));
        //1.判断该组织以及该组织下的子公司/部门是否有未离职员工
        String orgId = request.getOrgId();
        MbOrgInfo orgInfo = findByOrgId(orgId);
        if (orgInfo == null || BooleanUtils.isTrue(orgInfo.getIsBackground())) {
            return new DeleteResponse(1, "该组织不存在，删除失败", null);
        }
        int employeeSize = userOrgRelationService.countEmployee(UserOrgRelationStatusEnum.LEAVE.getStatus(), Lists.newArrayList(orgId));
        if (employeeSize > 0) {
            if (OrgTypeEnum.C.getCode().equals(orgInfo.getOrgType())) {
                return new DeleteResponse(1, "该公司已关联员工，不可删除", orgInfo.getId());
            } else {
                return new DeleteResponse(1, "该部门已关联员工，不可删除", orgInfo.getId());
            }
        }

        if(StringUtils.isBlank(orgInfo.getParentId())){
            MbOrgInfo defaultOrgInfo = new MbOrgInfo();
            defaultOrgInfo.setId(orgInfo.getId()*(-1));
            defaultOrgInfo = mbOrgInfoMapper.selectOne(defaultOrgInfo);
            if (defaultOrgInfo != null){
                employeeSize =  ObjectUtils.isEmpty(defaultOrgInfo) ? 0 : userOrgRelationService.countEmployee(UserOrgRelationStatusEnum.LEAVE.getStatus(), Lists.newArrayList(defaultOrgInfo.getOrgId()));
                if (employeeSize > 0) {
                    if (OrgTypeEnum.C.getCode().equals(orgInfo.getOrgType())) {
                        return new DeleteResponse(1, "该公司默认部门下有未处理员工，不可删除", orgInfo.getId());
                    } else {
                        return new DeleteResponse(1, "该公司默认部门下有未处理员工，不可删除", orgInfo.getId());
                    }
                }

                // 删除默认部门
                mbOrgInfoMapper.deleteByOrgId(defaultOrgInfo.getOrgId());
                // 删除相关组织设置
                orgConfigService.deleteOrgConfig(Lists.newArrayList(defaultOrgInfo.getOrgId()));
            }
        }


        //2.查出所有子孙级组织
        List<String> orgIds = listAllChildOrgIdsByOrgId(orgId);
        orgIds.remove(orgId);
        if (CollectionUtils.isNotEmpty(orgIds)) {
            //3.更新子孙级组织信息
//            List<MbOrgInfo> mbOrgInfoList = mbOrgInfoMapper.listByOrgIdsWithoutBackground(orgIds);
//            mbOrgInfoList.forEach(e -> {
//                if (Objects.equals(e.getParentId(), orgId)) {
//                    e.setParentId(orgInfo.getParentId());
//                }
//                e.setLevel(e.getLevel() - 1);
//                mbOrgInfoMapper.updateLevelAndParentIdByOrgId(e.getOrgId(), e.getLevel(), e.getParentId());
//            });
            employeeSize = userOrgRelationService.countEmployee(UserOrgRelationStatusEnum.LEAVE.getStatus(), Lists.newArrayList(orgIds));
            if (employeeSize > 0) {
                if (OrgTypeEnum.C.getCode().equals(orgInfo.getOrgType())) {
                    return new DeleteResponse(1, "该公司子部门下有未处理员工，不可删除", orgInfo.getId());
                } else {
                    return new DeleteResponse(1, "该部门子部门下有未处理员工，不可删除", orgInfo.getId());
                }
            }
            mbOrgInfoMapper.deleteByOrgIds(orgIds);
            // 删除相关组织设置
            orgConfigService.deleteOrgConfig(orgIds);
        }
        // 4.删除组织信息
        mbOrgInfoMapper.deleteByOrgId(orgId);
        // 删除相关组织设置
        orgConfigService.deleteOrgConfig(Lists.newArrayList(orgId));

        // 5.删除关联发票信息
        commonInvoiceInfoService.deleteByOrgId(orgId);

        // 6.删除关联配送信息
        expressAddressService.deleteByOrgId(orgId);

        // 7.删除关联支付信息
        orgPayTypeService.delete(Collections.singletonList(orgId), null, null, null, true);

        // 8.删除职级信息
        postService.deleteByOrgIds(Collections.singletonList(orgId));

        // 9.删除成本中心
        costCenterService.deleteByOrgId(orgId);

        deleteOperateLog(String.valueOf(orgIds));

        //删除部门   (需查询是否关联角色, 清除角色--部门中间表数据)
        delRoleOrgDataInfo(baseUserInfo, orgInfo);

        return new DeleteResponse(0, "刪除成功", orgInfo.getId());
    }

    /**
     *  部门删除  (数据权限)    需同步删除与角色关联得数据节点
     * @param baseUserInfo
     * @param orgInfo
     */
    @Override
    public void delRoleOrgDataInfo(BaseUserInfo baseUserInfo, MbOrgInfo orgInfo) {
        if (baseUserInfo != null && !baseUserInfo.getBgUser()) {
            mbRoleResourceService.delRoleOrg(baseUserInfo.getRoleId(), Arrays.asList(orgInfo.getId()), ResourceEnum.DEPT.getCode());
            roleResourceService.delOneRoleResourceData(baseUserInfo.getRoleId(), orgInfo.getId(), ResourceEnum.DEPT.getCode());
            return;
        }
        List<Long> roleIdByOrgId = mbRoleResourceService.findRoleIdByOrgId(orgInfo.getId());
        if (CollectionUtils.isNotEmpty(roleIdByOrgId)) {
            roleIdByOrgId.stream().forEach(a -> {
                roleResourceService.delOneRoleResourceData(a, orgInfo.getId(), ResourceEnum.DEPT.getCode());
                mbRoleResourceService.delRoleOrg(a, Arrays.asList(orgInfo.getId()), ResourceEnum.DEPT.getCode());
            });
        }
    }


    @Override
    public boolean updateBaseOrgInfo(MbOrgInfo mbOrgInfo) {
        if (mbOrgInfo == null || StringUtils.isEmpty(mbOrgInfo.getOrgId())) {
            return false;
        }
        return this.updateByExampleSelective(mbOrgInfo) > 0;
    }
    @Override
    public boolean updateParentBusinessCode(String businessCode, String newBusinessCode) {
        if (StringUtils.isEmpty(businessCode) || StringUtils.isEmpty(newBusinessCode)) {
            return false;
        }
        return mbOrgInfoMapper.updateParentBusinessCode(businessCode, newBusinessCode) > 0;
    }

    @Override
    public int batchInsertOrgInfo(List<MbOrgInfo> mbOrgInfoList) {
        if (CollectionUtils.isEmpty(mbOrgInfoList)){
            return 0;
        }
        return mbOrgInfoMapper.insertList(mbOrgInfoList);
    }

    @Override
    public int deleteByOrgIds(List<String> orgIds) {
        return mbOrgInfoMapper.deleteByOrgIds(orgIds);
    }

    @Override
    public JSONResult<Map> findAllCompanyInfoGroupByLevel(BaseUserInfo baseUserInfo) {
        // 查找所有公司orgId name
        List<MbOrgInfo> allOrgInfoList = listAll();
        if (baseUserInfo.getDataPermissionControl()) {
            ResourceInfo resourceInfo = manager.getResource(String.valueOf(baseUserInfo.getRoleId()), ResourceInfo.class);
            Set<String> collect = resourceInfo.getDeptInfos().stream().map(ResourceInfo.DeptInfo::getOrgId).collect(Collectors.toSet());

            //判断如果走数据权限   全部为部门则获取当前登陆卡公司返回
            if (resourceInfo.getDeptInfos().stream().allMatch(a -> Objects.equals("D", a.getOrgType()))) {
                collect.add(baseUserInfo.getCorpId());
            }
            allOrgInfoList = allOrgInfoList.stream().filter(i -> collect.contains(i.getOrgId())).collect(Collectors.toList());
        }

        Map<String, MbOrgInfo> permissionOrgMap = allOrgInfoList.stream().collect(Collectors.toMap(item -> item.getOrgId(), Function.identity(), (k1, k2) -> k1));

        Map<String, List<RoutCompanyVo>> levelMap = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(allOrgInfoList)) {
            List<MbOrgInfo> companyList = allOrgInfoList.stream().filter(p -> p.getOrgType().equals(OrganizationConst.COMPANY)).collect(Collectors.toList());
            List<RoutCompanyVo> allOrgList = companyList.stream().map(bean -> {
                return new RoutCompanyVo(bean.getParentId(), bean.getOrgId(), String.format("%s(%s)", bean.getName(), OrgTypeEnum.getByCode(bean.getOrgType()).getDesc()), bean.getLevel(), bean.getOrgType());
            }).collect(Collectors.toList());

            Map<String, List<RoutCompanyVo>> newLevelMap = Maps.newHashMap();
            if (CollectionUtils.isNotEmpty(allOrgList)) {
                Map<Integer, List<RoutCompanyVo>> levelIntMap = allOrgList.stream().collect(Collectors.groupingBy(RoutCompanyVo::getLevel));
                for (Integer level : levelIntMap.keySet()) {
                    levelMap.put(String.valueOf(level), levelIntMap.get(level));
                }
                for (String level : levelMap.keySet()) {
                    List<RoutCompanyVo> everyLevelOrgList = levelMap.get(level);
                    for (RoutCompanyVo companyVo:everyLevelOrgList){
                        if (StringUtils.isBlank(companyVo.getParentId())){
                            continue;
                        }
                        MbOrgInfo mbOrgInfo = permissionOrgMap.get(companyVo.getParentId());
                        if (Objects.isNull(mbOrgInfo)){
                            continue;
                        }

                        if (!OrgTypeEnum.D.getCode().equals(mbOrgInfo.getOrgType())){
                            continue;
                        }

                        int levelNum = Integer.parseInt(level) - 1;
                        List<RoutCompanyVo> routCompanyVos = levelMap.get(String.valueOf(levelNum));
                        if (CollectionUtils.isEmpty(routCompanyVos)){
                            List<RoutCompanyVo> routCompanyVoList = newLevelMap.get(String.valueOf(levelNum));
                            if (CollectionUtils.isEmpty(routCompanyVoList)){
                                routCompanyVoList = new ArrayList<>();
                            }
                            Optional<RoutCompanyVo> first = routCompanyVoList.stream().filter(item -> item.getOrgId().equals(mbOrgInfo.getOrgId())).findFirst();
                            if (first.isPresent()){
                                continue;
                            }
                            routCompanyVoList.add(new RoutCompanyVo(mbOrgInfo.getParentId(), mbOrgInfo.getOrgId(), String.format("%s(%s)", mbOrgInfo.getName(), OrgTypeEnum.getByCode(mbOrgInfo.getOrgType()).getDesc()), mbOrgInfo.getLevel(), mbOrgInfo.getOrgType()));
                            newLevelMap.put(String.valueOf(levelNum), routCompanyVoList);
                        } else {
                            Optional<RoutCompanyVo> first = routCompanyVos.stream().filter(item -> item.getOrgId().equals(mbOrgInfo.getOrgId())).findFirst();
                            if (first.isPresent()){
                                continue;
                            }
                            routCompanyVos.add(new RoutCompanyVo(mbOrgInfo.getParentId(), mbOrgInfo.getOrgId(), String.format("%s(%s)", mbOrgInfo.getName(), OrgTypeEnum.getByCode(mbOrgInfo.getOrgType()).getDesc()), mbOrgInfo.getLevel(), mbOrgInfo.getOrgType()));
                            newLevelMap.put(String.valueOf(levelNum), routCompanyVos);
                        }

                        addDepartment(levelMap, newLevelMap, permissionOrgMap, mbOrgInfo.getParentId(), levelNum);
                    }
                }
                levelMap.putAll(newLevelMap);
            }
        }

        Map<String, List<RoutCompanyVo>> responseMap = sortByKey(levelMap);
        log.info("levelMap : " + JsonUtils.toJsonString(responseMap));
        return new JSONResult<>(responseMap);
    }

    private void addDepartment(Map<String, List<RoutCompanyVo>> levelMap, Map<String, List<RoutCompanyVo>> newLevelMap, Map<String, MbOrgInfo> permissionOrgMap, String parentId, int levelNum){
        MbOrgInfo mbOrgInfo = permissionOrgMap.get(parentId);
        if (Objects.isNull(mbOrgInfo)){
            return;
        }
        if (!OrgTypeEnum.D.getCode().equals(mbOrgInfo.getOrgType())){
            return;
        }

        levelNum = levelNum - 1;
        List<RoutCompanyVo> routCompanyVos = levelMap.get(String.valueOf(levelNum));
        if (CollectionUtils.isEmpty(routCompanyVos)){
            List<RoutCompanyVo> routCompanyVoList = newLevelMap.get(String.valueOf(levelNum));
            if (CollectionUtils.isEmpty(routCompanyVoList)){
                routCompanyVoList = new ArrayList<>();
            }
            Optional<RoutCompanyVo> first = routCompanyVoList.stream().filter(item -> item.getOrgId().equals(mbOrgInfo.getOrgId())).findFirst();
            if (first.isPresent()){
                return;
            }
            routCompanyVoList.add(new RoutCompanyVo(mbOrgInfo.getParentId(), mbOrgInfo.getOrgId(), String.format("%s(%s)", mbOrgInfo.getName(), OrgTypeEnum.getByCode(mbOrgInfo.getOrgType()).getDesc()), mbOrgInfo.getLevel(), mbOrgInfo.getOrgType()));
            newLevelMap.put(String.valueOf(levelNum), routCompanyVoList);
        } else {
            Optional<RoutCompanyVo> first = routCompanyVos.stream().filter(item -> item.getOrgId().equals(mbOrgInfo.getOrgId())).findFirst();
            if (first.isPresent()){
                return;
            }
            routCompanyVos.add(new RoutCompanyVo(mbOrgInfo.getParentId(), mbOrgInfo.getOrgId(), String.format("%s(%s)", mbOrgInfo.getName(), OrgTypeEnum.getByCode(mbOrgInfo.getOrgType()).getDesc()), mbOrgInfo.getLevel(), mbOrgInfo.getOrgType()));
        }

        newLevelMap.put(String.valueOf(levelNum), routCompanyVos);
    }

    private Map<String, List<RoutCompanyVo>> sortByKey(Map<String, List<RoutCompanyVo>> levelMap) {
        if (CollectionUtils.isEmpty(levelMap)) {
            Collections.emptyMap();
        }
        Map<String, List<RoutCompanyVo>> responseMap = new HashMap<>();
        int asInt = levelMap.keySet().stream().mapToInt(Integer::valueOf).min().getAsInt();
        int difference = asInt - 1;
        levelMap.forEach(
                (level, value) -> {
                    responseMap.put(String.valueOf(Integer.valueOf(level) - difference), value);
                }
        );
        return responseMap;
    }


    @Override
    public JSONResult<RoutCompanyVo> searchComapny(String keyword) {
        List<MbOrgInfo> allOrgInfoList = listAll();

        return null;
    }

    @Override
    public boolean createOrgInfo(MbOrgInfo mbOrgInfo) {
        int i = mbOrgInfoMapper.insertSelective(mbOrgInfo);
        return i > 0;
    }

    @Override
    public boolean insertMbOrgInfo(MbOrgInfo mbOrgInfo){
        int i = mbOrgInfoMapper.insertMbOrgInfo(mbOrgInfo);
        return i > 0;
    }


    @Override
    public boolean update(MbOrgInfo mbOrgInfo) {
        Example example = new Example(MbOrgInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(OrganizationConst.ORG_ID, mbOrgInfo.getOrgId());
        criteria.andEqualTo(OrganizationConst.IS_BACKGROUND, false);
        criteria.andEqualTo(CommonConst.DELETE_TIME, new Date(0));
        int i = mbOrgInfoMapper.updateByExampleSelective(mbOrgInfo, example);
        return i > 0;
    }

    @Override
    public MbOrgInfo findByOrgId(String orgId) {
        if (StringUtils.isBlank(orgId)) {
            return null;
        }
        MbOrgInfo mbOrgInfo = new MbOrgInfo();
        mbOrgInfo.setOrgId(orgId);
//        mbOrgInfo.setIsDeleted(false);
        mbOrgInfo.setDeleteTime(new Date(0));
        return mbOrgInfoMapper.selectOne(mbOrgInfo);
    }

    @Override
    public MbOrgInfo findById(Long id) {
        MbOrgInfo mbOrgInfo = new MbOrgInfo();
        mbOrgInfo.setId(id);
//        mbOrgInfo.setIsDeleted(false);
        mbOrgInfo.setDeleteTime(new Date(0));
        return mbOrgInfoMapper.selectOne(mbOrgInfo);
    }


    @Override
    public MbOrgInfo findByOrgId(String orgId, Boolean withDeleted) {
        MbOrgInfo mbOrgInfo = new MbOrgInfo();
        mbOrgInfo.setOrgId(orgId);
        if (!Boolean.TRUE.equals(withDeleted)) {
//            mbOrgInfo.setIsDeleted(false);
            mbOrgInfo.setDeleteTime(new Date(0));
        }
        return mbOrgInfoMapper.selectOne(mbOrgInfo);
    }

    @Override
    public List<OrgInfoVo> getParentOrgInfoList(String parentOrgId, int parentLevel, boolean isAll) {
        if (parentOrgId == null) {
            return null;
        }
        List<OrgInfoVo> orgInfoVoList = new ArrayList<>();
        for (int i = parentLevel; i > 0; i--) {
            MbOrgInfo mbOrgInfo = new MbOrgInfo();
            mbOrgInfo.setOrgId(parentOrgId);
//            mbOrgInfo.setIsDeleted(false);
            mbOrgInfo.setDeleteTime(new Date(0));
            MbOrgInfo mbOrgInfoItem = mbOrgInfoMapper.selectOne(mbOrgInfo);
            if (mbOrgInfoItem == null) {
                continue;
            }
            orgInfoVoList.add(CommonUtil.copyProperties(mbOrgInfoItem, OrgInfoVo.class));
            parentOrgId = mbOrgInfoItem.getParentId();
            //非查询到顶层
            if (!isAll || parentOrgId == null) {
                break;
            }
        }
        return orgInfoVoList;
    }

    @Override
    public List<OrgInfoVo> getOrgInfoList(String orgId, boolean isAll) {
        if (StringUtils.isBlank(orgId)){
            return new ArrayList<>();
        }
        MbOrgInfo mbOrgInfo = new MbOrgInfo();
        mbOrgInfo.setOrgId(orgId);
//        mbOrgInfo.setIsDeleted(false);
        mbOrgInfo.setDeleteTime(new Date(0));
        MbOrgInfo result = mbOrgInfoMapper.selectOne(mbOrgInfo);
        if (result == null) {
            return new ArrayList<>();
        }
        return getParentOrgInfoList(result.getOrgId(), result.getLevel(), true);
    }

    @Override
    public List<MbOrgInfo> listAll() {
        MbOrgInfo mbOrgInfo = new MbOrgInfo();
//        mbOrgInfo.setIsDeleted(false);
        mbOrgInfo.setDeleteTime(new Date(0));
        mbOrgInfo.setIsBackground(false);
        return mbOrgInfoMapper.select(mbOrgInfo);
    }

    @Override
    public List<OrgInfoAllDto> getOrgAllSomeParams() {
        return mbOrgInfoMapper.getOrgAllSomeParams();
    }

    @Override
    public List<MbOrgInfo> listNameByOrgIds(List<String> orgIds) {
        return mbOrgInfoMapper.listByOrgIds(orgIds);
    }

    @Override
    public List<MbOrgInfo> listByOrgIds(List<String> orgIds) {
        if (CollectionUtils.isEmpty(orgIds)) {
            return new ArrayList<>();
        }
        return mbOrgInfoMapper.listByOrgIdsWithoutBackground(orgIds);
    }

    @Override
    public List<MbOrgInfo> listCompanyByBusinessCodes( List<String> businessCodes) {
        if (CollectionUtils.isEmpty(businessCodes)) {
            return new ArrayList<>();
        }
        return mbOrgInfoMapper.listCompanyByBusinessCodes(businessCodes);
    }


    @Override
    public List<MbOrgInfo> listAllByOrgIds(List<String> orgIds) {
        if (CollectionUtils.isEmpty(orgIds)) {
            return new ArrayList<>();
        }
        return mbOrgInfoMapper.listAllByOrgIds(orgIds);
    }

    @Override
    public List<OrgAndDataPermissionInfoBO> wholeOrgTree(GetOrgTreeReq request) {
        List<MbOrgInfo> mbOrgInfos = mbOrgInfoMapper.selectAll();
        BaseUserInfo userInfo = UserInfoContext.getContextParams(BaseUserInfo.class);
        Set<String> dataPermissionSet = Optional.ofNullable(DataPermissionsContext.getRoleAllDataPermissions()).map(resource->{

                    if(request.getIsShowDefaultOrg()){
                        //开票
                        return resource.getInvoiceInfos();
                    }else {
                        return resource.getDeptInfos();
                    }
                })
                .orElse(new ArrayList<>()).stream().map(ResourceInfo.DeptInfo::getOrgId).collect(Collectors.toSet());

        List<OrgAndDataPermissionInfoBO> res = mbOrgInfos
                .stream()
                .filter(org -> Lists.newArrayList(OrgTypeEnum.C.getCode(), OrgTypeEnum.G.getCode()).contains(org.getOrgType()))
                .map(org -> {
                    return OrgAndDataPermissionInfoBO.builder()
                            .orgType(org.getOrgType())
                            .orgId(org.getOrgId())
                            .parentOrgId(org.getParentId())
                            .hasDataPermission(Boolean.TRUE.equals(userInfo.getBgUser()) ? userInfo.getBgUser() : dataPermissionSet.contains(org.getOrgId()))
                            .build();
                }).collect(Collectors.toList());

        Map<String, List<MbOrgInfo>> parentMap = mbOrgInfos
                .stream()
                .filter(org -> StringUtils.isNotBlank(org.getParentId()))
                .collect(Collectors.groupingBy(MbOrgInfo::getParentId));

        for (OrgAndDataPermissionInfoBO infoBO : res) {
            buildOrgTree(infoBO, parentMap, dataPermissionSet, userInfo);
        }
        return res;
    }

    public void buildOrgTree (OrgAndDataPermissionInfoBO infoBO, Map<String, List<MbOrgInfo>> parentMap,
                                                    Set<String> dataPermissionSet, BaseUserInfo userInfo) {
        List<MbOrgInfo> subOrgList = parentMap.get(infoBO.getOrgId());
        infoBO.setSubOrgInfoList(new ArrayList<>());
        if (CollectionUtils.isNotEmpty(subOrgList)) {
            for (MbOrgInfo org : subOrgList) {
                if (!Lists.newArrayList(OrgTypeEnum.C.getCode(), OrgTypeEnum.G.getCode()).contains(org.getOrgType())) {
                    OrgAndDataPermissionInfoBO bo = OrgAndDataPermissionInfoBO.builder()
                            .orgType(org.getOrgType())
                            .orgId(org.getOrgId())
                            .parentOrgId(org.getParentId())
                            .hasDataPermission(Boolean.TRUE.equals(userInfo.getBgUser()) ? userInfo.getBgUser() : dataPermissionSet.contains(org.getOrgId()))
                            .build();
                    buildOrgTree(bo,parentMap, dataPermissionSet, userInfo);
                    infoBO.getSubOrgInfoList().add(bo);
                }
            }
        }
    }

    @Override
    public List<MbOrgInfo> listByIds(List<String> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return new ArrayList<>();
        }
        return mbOrgInfoMapper.listByIdsWithoutBackground(ids);
    }

    @Override
    public List<MbOrgEmployeeInfoDto> batchFindRecentCompanyIdByOrgId(List<MbOrgEmployeeInfo> list) {
        List<MbOrgEmployeeInfoDto> returnList = new ArrayList<>();
        List<MbOrgInfo> mbOrgInfoList = mbOrgInfoMapper.listAll();
        Map<String, MbOrgInfo> orgIdMap = mbOrgInfoList.stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, mbOrgInfo -> mbOrgInfo));
        for (MbOrgEmployeeInfo mbOrgEmployeeInfo : list) {
            String recentCompanyId = findRecentCompanyId(mbOrgEmployeeInfo.getOrgId(), orgIdMap);
            MbOrgEmployeeInfoDto mbOrgEmployeeInfoDto = new MbOrgEmployeeInfoDto();
            BeanUtils.copyProperties(mbOrgEmployeeInfo, mbOrgEmployeeInfoDto);
            if (StringUtils.isNotBlank(recentCompanyId)) {
                MbOrgInfo mbOrgInfo = orgIdMap.get(recentCompanyId);
                if (mbOrgInfo != null) {
                    mbOrgEmployeeInfoDto.setCompanyName(mbOrgInfo.getName());
                    mbOrgEmployeeInfoDto.setCompanyId(mbOrgInfo.getOrgId());
                }
            }
            if (StringUtils.isNotBlank(mbOrgEmployeeInfo.getOrgId())) {
                MbOrgInfo mbOrgInfo = orgIdMap.get(mbOrgEmployeeInfo.getOrgId());
                if (mbOrgInfo != null) {
                    mbOrgEmployeeInfoDto.setDeptName(mbOrgInfo.getName());
                }
            }
            returnList.add(mbOrgEmployeeInfoDto);
        }
        return returnList;
    }

    @Override
    public boolean updateContactInfo(MbOrgInfo mbOrgInfo) {
        return this.updateByExampleSelective(mbOrgInfo) > 0;
    }

    @Override
    public int updateByOrgId(MbOrgInfo mbOrgInfo) {
        return this.updateByExampleSelective(mbOrgInfo);
    }

    @Override
    public int batchUpdate(List<MbOrgInfo> mbOrgInfoList) {
        return mbOrgInfoMapper.batchUpdate(mbOrgInfoList);
    }

    public int updateByExampleSelective(MbOrgInfo mbOrgInfo) {
        if (mbOrgInfo == null) {
            return 0;
        }
        Example example = new Example(MbOrgInfo.class);
        example.createCriteria().andEqualTo("orgId", mbOrgInfo.getOrgId()).andEqualTo("deleteTime", new Date(0));
        return mbOrgInfoMapper.updateByExampleSelective(mbOrgInfo, example);
    }

    @Override
    public boolean batchUpdateStatus(List<String> orgIds, String status) {
        return mbOrgInfoMapper.batchUpdateOrgValid(orgIds, status) > 0;
    }

    @Override
    public String findOrgPath(String orgId) {
        List<MbOrgInfo> mbOrgInfoList = mbOrgInfoMapper.listAll();
        Map<String, MbOrgInfo> orgInfoMap = mbOrgInfoList.stream().filter(p -> StringUtils.isNotBlank(p.getOrgId())).collect(Collectors.toMap(MbOrgInfo::getOrgId, p -> p));
        String recentCompanyId = findRecentCompanyId(orgId, orgInfoMap);
        if (StrUtil.isEmpty(recentCompanyId)) {
            return "";
        }
        String rootCompanyId = findRootCompanyId(orgId, orgInfoMap);
        if (recentCompanyId.equals(rootCompanyId)) {
            return orgInfoMap.get(rootCompanyId).getName();
        }
        if (recentCompanyId.equals(orgId)) {
            return orgInfoMap.get(rootCompanyId).getName() + ">" + orgInfoMap.get(recentCompanyId).getName();
        }
        return orgInfoMap.get(rootCompanyId).getName() + ">" + orgInfoMap.get(recentCompanyId).getName() + ">" + orgInfoMap.get(orgId).getName();
    }


    @Override
    public List<MbOrgInfo> fuzzyByName(String keyWord) {
        return mbOrgInfoMapper.fuzzyByName(keyWord);
    }

    /**
     * 模糊查询前台组织结构
     */
    @Override
    public List<MbOrgInfo> fuzzyByNameAndType(String keyWord, String orgType) {
        return this.fuzzyByNameAndType(keyWord, orgType, "T");
    }

    @Override
    public List<MbOrgInfo> listAllCompany(Integer pageSize, Integer pageNum) {
        if (pageSize != null && pageNum != null) {
            return mbOrgInfoMapper.listAllCompany(pageSize * pageNum, pageSize);
        }
        return mbOrgInfoMapper.listAllCompany(null, null);
    }

    @Override
    public List<MbOrgInfo> listAllCompanyWithDeleted(Integer pageSize, Integer pageNum) {
        if (pageSize != null && pageNum != null) {
            return mbOrgInfoMapper.listAllCompanyWithDeleted(pageSize * pageNum, pageSize);
        }
        return mbOrgInfoMapper.listAllCompanyWithDeleted(null, null);
    }

    @Override
    public boolean batchUpdateOpenUnitePayment(List<String> orgIds, boolean openStatus) {
        return mbOrgInfoMapper.batchUpdateOpenUnitePayment(orgIds, openStatus) > 0;
    }

    private String findRootCompanyId(String orgId, Map<String, MbOrgInfo> orgInfoMap) {
        MbOrgInfo mbOrgInfo = orgInfoMap.get(orgId);
        if (mbOrgInfo.getLevel() == 1 && mbOrgInfo.getOrgType().equals(OrganizationConst.COMPANY)) {
            return mbOrgInfo.getOrgId();
        }
        String parentId = mbOrgInfo.getParentId();
        return findRootCompanyId(parentId, orgInfoMap);
    }

    /**
     * 查询指定orgId的直系父级orgIds
     *
     * @param orgId      指定orgid
     * @param orgInfoMap 全量组织数据
     * @param returnList 最终返回值
     */
    private void listAllParent(String orgId, Map<String, MbOrgInfo> orgInfoMap, List<String> returnList) {
        MbOrgInfo mbOrgInfo = orgInfoMap.get(orgId);
        if (mbOrgInfo != null) {
            returnList.add(mbOrgInfo.getOrgId());
            if (StrUtil.isNotEmpty(mbOrgInfo.getParentId())) {
                listAllParent(mbOrgInfo.getParentId(), orgInfoMap, returnList);
            }
        }
    }

    /**
     * 获取子部门信息
     *
     * @param orgId
     * @return
     */
    private List<MbOrgInfo> findChildDepOrgInfoByOrgId(String orgId) {
        List<MbOrgInfo> mbOrgInfoList = mbOrgInfoMapper.listAll();
        Map<String, List<MbOrgInfo>> parentMap = mbOrgInfoList.stream().filter(p -> StringUtils.isNotBlank(p.getParentId())).collect(Collectors.groupingBy(MbOrgInfo::getParentId));
        List<MbOrgInfo> returnList = new ArrayList<>();
        listAllChildDep(orgId, parentMap, returnList);

        MbOrgInfo mbOrgInfo = mbOrgInfoList.stream().filter(x -> orgId.equals(x.getOrgId())).findAny().orElse(null);
        if (mbOrgInfo != null) {
            returnList.add(mbOrgInfo);
        }

        return returnList;
    }

    private List<MbOrgInfo> listAllChildDep(String
                                                    orgId, Map<String, List<MbOrgInfo>> parentMap, List<MbOrgInfo> returnList) {
        List<MbOrgInfo> mbOrgInfoList = parentMap.get(orgId);
        if (CollectionUtils.isNotEmpty(mbOrgInfoList)) {
            for (MbOrgInfo mbOrgInfo : mbOrgInfoList) {
                if (!OrgTypeEnum.D.getCode().equals(mbOrgInfo.getOrgType())) {
                    continue;
                }
                returnList.add(mbOrgInfo);
                listAllChildDep(mbOrgInfo.getOrgId(), parentMap, returnList);
            }
        }
        return returnList;
    }

    @Override
    public void findAllChildOrgIdsByOrgId(String orgId, List<String> orgIds) {
        List<MbOrgInfo> mbOrgInfoList = mbOrgInfoMapper.listAll();
        Map<String, List<MbOrgInfo>> parentMap = mbOrgInfoList.stream().filter(p -> StringUtils.isNotBlank(p.getParentId())).collect(Collectors.groupingBy(MbOrgInfo::getParentId));
        listAllChild(orgId, parentMap, orgIds);
    }

    private List<String> listAllChild(String orgId, Map<String, List<MbOrgInfo>> parentMap, List<String> returnList) {
        List<MbOrgInfo> mbOrgInfoList = parentMap.get(orgId);
        if (CollectionUtils.isNotEmpty(mbOrgInfoList)) {
            for (MbOrgInfo mbOrgInfo : mbOrgInfoList) {
                returnList.add(mbOrgInfo.getOrgId());
                listAllChild(mbOrgInfo.getOrgId(), parentMap, returnList);
            }
        }
        return returnList;
    }

    @Override
    public List<String> listAllChildOrgIdsByOrgId(String id) {
        List<String> orgIds = new ArrayList<>();
        findAllChildOrgIdsByOrgId(id, orgIds);
        orgIds.add(id);
        return orgIds;
    }

    /**
     * 查询部门直属公司
     * @param departmentId
     * @return
     */
    @Override
    public MbOrgInfo findRecentCompanyIdByOrgId(String departmentId) {
        List<MbOrgInfo> mbOrgInfoList = mbOrgInfoMapper.listAll();
        Map<String, MbOrgInfo> orgIdMap = mbOrgInfoList.stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, mbOrgInfo -> mbOrgInfo));
        String recentCompanyId = findRecentCompanyId(departmentId, orgIdMap);
        return orgIdMap.get(recentCompanyId);
    }

    public MbOrgInfo findRecentCompanyIdByOrgId(String departmentId,List<MbOrgInfo> allMbOrgInfoList) {
        Map<String, MbOrgInfo> orgIdMap = allMbOrgInfoList.stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, mbOrgInfo -> mbOrgInfo));
        String recentCompanyId = findRecentCompanyId(departmentId, orgIdMap);
        return orgIdMap.get(recentCompanyId);
    }

    /**
     * 查询组织直属顶级第一级公司
     * @param orgId
     * @return
     */
    @Override
    public MbOrgInfo findFirstCorpInfo(String orgId){
        List<MbOrgInfo> mbOrgInfoList = mbOrgInfoMapper.listAll();
        Map<String, MbOrgInfo> orgIdMap = mbOrgInfoList.stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, mbOrgInfo -> mbOrgInfo));
        String firstCompanyId = findFirstCompanyId(orgId, orgIdMap);
        return orgIdMap.get(firstCompanyId);
    }

    /**
     * 获取上级第一个类型为公司的组织
     * @param orgId
     * @return
     */
    @Override
    public MbOrgInfo findFirstCompany(String orgId) {
        if (StringUtils.isBlank(orgId)){
            return null;
        }
        Example example = new Example(MbOrgInfo.class);
        example.createCriteria().andEqualTo("orgId", orgId);
        List<MbOrgInfo> infoList = mbOrgInfoMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(infoList)){
            MbOrgInfo mbOrgInfo = infoList.get(0);
            if(OrgTypeEnum.C.getCode().equalsIgnoreCase(mbOrgInfo.getOrgType()) || StringUtils.isBlank(mbOrgInfo.getParentId())){
                return mbOrgInfo;
            } else {
                return findFirstCompany(mbOrgInfo.getParentId());
            }
        }
        return null;
    }


    @Override
    public List<String> listRecentCompanyAllDepartmentByOrgId(String orgId) {
        List<MbOrgInfo> mbOrgInfoList = mbOrgInfoMapper.listAll();
        Map<String, MbOrgInfo> orgIdMap = mbOrgInfoList.stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, mbOrgInfo -> mbOrgInfo));
        Map<String, List<MbOrgInfo>> parentIdMapList = mbOrgInfoList.stream().filter(mbOrgInfo -> StringUtils.isNotBlank(mbOrgInfo.getParentId())).collect(Collectors.groupingBy(MbOrgInfo::getParentId));
        String recentCompanyId = findRecentCompanyId(orgId, orgIdMap);
        List<String> departmentIds = new ArrayList<>();
        listAllDepartmentIdsByCompanyId(recentCompanyId, parentIdMapList, departmentIds);
        return departmentIds;
    }

    @Override
    public List<String> listRecentCompanyAllOrgIds(String orgId) {
        List<MbOrgInfo> mbOrgInfoList = mbOrgInfoMapper.listAll();
        Map<String, MbOrgInfo> orgIdMap = mbOrgInfoList.stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, mbOrgInfo -> mbOrgInfo));
        Map<String, List<MbOrgInfo>> parentIdMapList = mbOrgInfoList.stream().filter(mbOrgInfo -> StringUtils.isNotBlank(mbOrgInfo.getParentId())).collect(Collectors.groupingBy(MbOrgInfo::getParentId));
        String recentCompanyId = findRecentCompanyId(orgId, orgIdMap);
        List<String> departmentIds = new ArrayList<>();
        departmentIds.add(recentCompanyId);
        listAllOrgIdsByCompanyId(recentCompanyId, parentIdMapList, departmentIds);
        return departmentIds;
    }

    @Override
    public List<String> listAllDepartmentByOrgId(String orgId) {
        List<MbOrgInfo> mbOrgInfoList = mbOrgInfoMapper.listAll();
        Map<String, List<MbOrgInfo>> parentIdMapList = mbOrgInfoList.stream().filter(mbOrgInfo -> StringUtils.isNotBlank(mbOrgInfo.getParentId())).collect(Collectors.groupingBy(MbOrgInfo::getParentId));
        List<String> departmentIds = CollUtil.newArrayList(orgId);
        listAllDepartmentIdsByCompanyId(orgId, parentIdMapList, departmentIds);
        return departmentIds;
    }
    @Override
    public List<String> listAllDepartmentByOrgId(GetOrgTreeRequest request) {
        List<MbOrgInfo> mbOrgInfoList = mbOrgInfoMapper.listAll();
        Map<String, List<MbOrgInfo>> parentIdMapList = mbOrgInfoList.stream().filter(mbOrgInfo -> StringUtils.isNotBlank(mbOrgInfo.getParentId())).collect(Collectors.groupingBy(MbOrgInfo::getParentId));
        List<String> departmentIds = CollUtil.newArrayList(request.getOrgId());
        listAllDepartmentIdsByCompanyId(request.getOrgId(), parentIdMapList, departmentIds,request.getIsErgodic());
        return departmentIds;
    }

    /**
     * 查询组织下所有子部门（不包含该组织），不穿透子公司
     */
    @Override
    public List<MbOrgInfo> listAllDepartments(String orgId, Boolean withDeleted) {
        List<MbOrgInfo> mbOrgInfoList = Lists.newArrayList();
        if (Boolean.TRUE.equals(withDeleted)) {
            mbOrgInfoList.addAll(mbOrgInfoMapper.listAllWithDeleted());
        } else {
            mbOrgInfoList.addAll(mbOrgInfoMapper.listAll());
        }
        Map<String, List<MbOrgInfo>> parentIdMapList = mbOrgInfoList.stream().filter(mbOrgInfo -> StringUtils.isNotBlank(mbOrgInfo.getParentId())).collect(Collectors.groupingBy(MbOrgInfo::getParentId));
        List<String> departmentIds = CollUtil.newArrayList();
        listAllDepartmentIdsByCompanyId(orgId, parentIdMapList, departmentIds);
        List<MbOrgInfo> result = mbOrgInfoList.stream().filter(o -> departmentIds.contains(o.getOrgId())).collect(Collectors.toList());
        return result;
    }

    /**
     * 查询组织下直属子部门（不包含该组织），不穿透子公司
     */
    @Override
    public List<MbOrgInfo> listAllDepartmentsByParentId(String parentId, Boolean withDeleted) {
        MbOrgInfo queryParam = new MbOrgInfo();
        queryParam.setParentId(parentId);
        queryParam.setOrgType(OrgTypeEnum.D.getCode());
        if (!Boolean.TRUE.equals(withDeleted)) {
            queryParam.setDeleteTime(new Date(0));
        }
        return mbOrgInfoMapper.select(queryParam);
    }

    /**
     * 查询组织下所有子部门id（不包含该组织），不穿透子公司
     * ture 包含已删除得
     */
    @Override
    public List<String> listAllDepartmentIds(String orgId, Boolean withDeleted) {
        List<MbOrgInfo> mbOrgInfoList = Lists.newArrayList();
        if (Boolean.TRUE.equals(withDeleted)) {
            mbOrgInfoList.addAll(mbOrgInfoMapper.listAllWithDeleted());
        } else {
            mbOrgInfoList.addAll(mbOrgInfoMapper.listAll());
        }
        Map<String, List<MbOrgInfo>> parentIdMapList = mbOrgInfoList.stream().filter(mbOrgInfo -> StringUtils.isNotBlank(mbOrgInfo.getParentId())).collect(Collectors.groupingBy(MbOrgInfo::getParentId));
        List<String> departmentIds = CollUtil.newArrayList();
        listAllDepartmentIdsByCompanyId(orgId, parentIdMapList, departmentIds);
        return departmentIds;
    }

    @Override
    public List<String> listAllDepartmentIds(String orgId, Boolean withDeleted, Boolean penetrate) {
        List<MbOrgInfo> mbOrgInfoList = Lists.newArrayList();
        if (Boolean.TRUE.equals(withDeleted)) {
            mbOrgInfoList.addAll(mbOrgInfoMapper.listAllWithDeleted());
        } else {
            mbOrgInfoList.addAll(mbOrgInfoMapper.listAll());
        }
        Map<String, List<MbOrgInfo>> parentIdMapList = mbOrgInfoList.stream().filter(mbOrgInfo -> StringUtils.isNotBlank(mbOrgInfo.getParentId())).collect(Collectors.groupingBy(MbOrgInfo::getParentId));
        List<String> departmentIds = CollUtil.newArrayList();
        listAllDepartmentIdsByCompanyId(orgId, parentIdMapList, departmentIds,true);
        return departmentIds;
    }
    /**
     * 查询组织下（不包含该组织）所有子公司id
     */
    @Override
    public List<String> listAllCorpIds(String orgId, Boolean withDeleted) {
        List<MbOrgInfo> mbOrgInfoList = Lists.newArrayList();
        if (Boolean.TRUE.equals(withDeleted)) {
            mbOrgInfoList.addAll(mbOrgInfoMapper.listAllWithDeleted());
        } else {
            mbOrgInfoList.addAll(mbOrgInfoMapper.listAll());
        }
        Map<String, List<MbOrgInfo>> parentIdMapList = mbOrgInfoList.stream().filter(mbOrgInfo -> StringUtils.isNotBlank(mbOrgInfo.getParentId())).collect(Collectors.groupingBy(MbOrgInfo::getParentId));
        Map<String, MbOrgInfo> orgMap = mbOrgInfoList.stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, Function.identity(), (oldData, newData) -> newData));
        List<String> orgIds = CollUtil.newArrayList();
        listAllChild(orgId, parentIdMapList, orgIds);
        orgIds = orgIds.stream().filter(o -> {
            MbOrgInfo orgInfo = orgMap.get(o);
            if (orgInfo != null && OrgTypeEnum.C.getCode().equals(orgInfo.getOrgType())) {
                //过滤公司
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        return orgIds;
    }

    @Override
    public List<String> listRecentCompanyDirectDepartmentWithCompanyByOrgId(String orgId) {
        List<MbOrgInfo> mbOrgInfoList = mbOrgInfoMapper.listAll();
        Map<String, MbOrgInfo> orgIdMap = mbOrgInfoList.stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, mbOrgInfo -> mbOrgInfo));
        Map<String, List<MbOrgInfo>> parentIdMapList = mbOrgInfoList.stream().filter(mbOrgInfo -> StringUtils.isNotBlank(mbOrgInfo.getParentId())).collect(Collectors.groupingBy(MbOrgInfo::getParentId));
        String recentCompanyId = findRecentCompanyId(orgId, orgIdMap);
        List<String> departmentIds = CollUtil.newArrayList(recentCompanyId);
        listDirectDepartmentIdsByCompanyId(recentCompanyId, parentIdMapList, departmentIds);
        return departmentIds;
    }

    /**
     * 模糊查询公司
     *
     * @param name    name
     * @param orgType
     * @return list
     */
    @Override
    public List<CompanyVo> getCompaniesByName(String name, String orgType, BaseUserInfo baseUserInfo) {
        List<MbOrgInfo> companyInfoList = mbOrgInfoMapper.listAllByOrgType(orgType);
        if (baseUserInfo != null && baseUserInfo.getDataPermissionControl()) {
            ResourceInfo resourceInfo = manager.getResource(String.valueOf(baseUserInfo.getRoleId()), ResourceInfo.class);
            Set<Long> ids = Optional.ofNullable(resourceInfo.getDeptInfos()).orElse(Lists.newArrayList()).stream().map(ResourceInfo.DeptInfo::getId).collect(Collectors.toSet());
            companyInfoList = companyInfoList.stream().filter(i -> ids.contains(i.getId())).collect(Collectors.toList());
        }

        if (CollectionUtils.isEmpty(companyInfoList)) {
            return new ArrayList<>();
        }
        List<String> orgIds = companyInfoList.stream().filter(e -> StringUtils.contains(e.getName(), name)).map(MbOrgInfo::getOrgId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(orgIds)) {
            return new ArrayList<>();
        }
        List<MbOrgInfo> infos = mbOrgInfoMapper.listByOrgIds(orgIds);
        return infos.stream().map(i -> CompanyVo.builder().id(i.getId())
                .corpId(i.getOrgId()).name(i.getName()).build()).collect(Collectors.toList());
    }


    @Override
    public JSONResult<FfpPageVo> getFfpItems(FfpRequest request, BaseUserInfo baseUserInfo) {
        StringBuilder logContext = new StringBuilder();
        try{
            LogSplicingUtils.addLogContext(logContext, "获取常旅客信息");
            //Map<String, Object> returnMap = new HashMap<>(2);
            FfpPageVo ffpPageVo = new FfpPageVo();
            //当前用户id
            String uid = baseUserInfo.getUid();
            String orgId = baseUserInfo.getOrgId();

            // 查询用户信息
            MbOrgEmployeeInfo result = organizationEmployeeService.findByUid(uid);
            if (result == null) {
                LogSplicingUtils.addLogContext(logContext, "获取当前用户信息失败");
                return JSONResult.ok();
            }
            String query = request.getSelectVal();
            //查询代订范围
            // 能代订的组织结构范围
            List<String> orgIds = CollUtil.newArrayList(orgId);
            // 是否可以代订非员工
            BookingRange bookingRange = bookingRelationService.queryBookingRangeByUidAndOrgId(uid, orgId);
            if (bookingRange != null) {
                // 过滤掉状态为禁用的组织结构
                List<String> orgRange = bookingRange.getBookingRange();
                if (CollUtil.isNotEmpty(orgRange)) {
                    LogSplicingUtils.addLogContext(logContext, "uid-orgId:[%s-%s], 代订信息：%s", uid, orgId, JsonUtils.toJsonString(orgRange));
                    List<MbOrgInfo> mbOrgInfoList = this.listByOrgIds(orgRange);
                    if (CollUtil.isNotEmpty(mbOrgInfoList)) {
                        orgIds.addAll(mbOrgInfoList.stream().filter(p -> p.getValid().equals(CommonConst.TRUE)).map(MbOrgInfo::getOrgId).collect(Collectors.toList()));
                    }
                }
            }
            // 过滤掉重复数据
            orgIds = CollUtil.distinct(orgIds);
            LogSplicingUtils.addLogContext(logContext, "代订范围：%s", uid, orgId, JsonUtils.toJsonString(orgIds));
            //查询用户的所有员工
            Page<MbFreshPassengerRelation> pageInfo = freshPassengerRelationService.pageByUid(uid, orgId, query, request.getPageNum(), request.getPageSize());
            List<MbFreshPassengerRelation>  mbFreshPassengerRelations = pageInfo.getRecords();
            LogSplicingUtils.addLogContext(logContext, "查询到的常旅为：%s", uid, orgId, JsonUtils.toJsonString(mbFreshPassengerRelations));
            int totalPage = (int) pageInfo.getPages();
            long totalCount = pageInfo.getTotal();
            ffpPageVo.setShowAdd(true);
            if (CollectionUtils.isEmpty(mbFreshPassengerRelations)) {
                return JSONResult.success(ffpPageVo);
            }

            List<String> employeeUidList = mbFreshPassengerRelations.stream().filter(p -> p.getEmployeeFlag() == 1).distinct().map(MbFreshPassengerRelation::getFreshUid).collect(Collectors.toList());
            Map<String, List<MbOrgUserIdcard>> uidCardMapList = new HashMap<>(16);
            Map<String, MbOrgEmployeeInfo> employeeInfoMap = new HashMap<>(16);
            Map<String, List<MbUserOrgRelation>> userRelationMap = new HashMap<>();
            Map<String, MbUserLogin> userLoginMap = new HashMap<>(16);
            if (CollectionUtils.isNotEmpty(employeeUidList)) {
                // #1.员工证件信息
                List<MbOrgUserIdcard> userIdcards = organizationUserIdCardService.batchFindByUids(employeeUidList);
                uidCardMapList = userIdcards.stream().collect(Collectors.groupingBy(MbOrgUserIdcard::getEmployeeUid));
                // #2.员工信息
                List<MbOrgEmployeeInfo> mbOrgEmployeeInfos = organizationEmployeeService.listByUids(employeeUidList);
                employeeInfoMap = mbOrgEmployeeInfos.stream().collect(Collectors.toMap(MbOrgEmployeeInfo::getUid, p -> p));
                userRelationMap = userOrgRelationService.listByUids(employeeUidList).stream().collect(Collectors.groupingBy(x -> x.getUid()));

                // #3u员工登录信息
                List<MbUserLogin> userLogins = userLoginService.getByUids(employeeUidList);
                userLoginMap = userLogins.stream().collect(Collectors.toMap(MbUserLogin::getUid, userLogin -> userLogin, (k1, k2) -> k1));
            }

            List<Long> nonEmployeeUidList = mbFreshPassengerRelations.stream().filter(p -> p.getEmployeeFlag() == 0).map(x -> Long.valueOf(x.getFreshUid())).collect(Collectors.toList());
            Map<Long, List<MbOrgUserIdcard>> nonUidCardMapList = new HashMap<>(16);
            Map<Long, MbOrgNonEmployeeInfo> nonEmployeeInfoMap = new HashMap<>(16);
            if (CollectionUtils.isNotEmpty(nonEmployeeUidList)) {
                // #1.非员工证件信息
                List<MbOrgUserIdcard> nonEmpIdCards = organizationUserIdCardService.batchFindByNonEmployeeUids(nonEmployeeUidList);
                nonUidCardMapList = nonEmpIdCards.stream().collect(Collectors.groupingBy(MbOrgUserIdcard::getNonEmployeeId));
                // #2.非员工信息
                List<MbOrgNonEmployeeInfo> mbOrgNonEmployeeInfos = mbOrgNonEmployeeMapper.listByIds(nonEmployeeUidList);
                nonEmployeeInfoMap = mbOrgNonEmployeeInfos.stream().collect(Collectors.toMap(MbOrgNonEmployeeInfo::getId, p -> p));
            }

            FrequentCardListBean bean;

            Map map = Maps.newHashMap();//返回规范
            //常旅卡
            JSONResult<List<FrequencyVo>> jsonResult = fpCardApiService.ffpCardList();
            Map<String, FrequentPassengerDto> frequentPassengerDtoMap = null;
            if (jsonResult.isSUCCESS()) {
                List<FrequencyVo> frequencyVoList = jsonResult.getData();
                frequentPassengerDtoMap = frequencyVoList.stream().map(x -> x.getChildren()).reduce(BaseUtils::combine).orElse(new ArrayList<>())
                        .stream().collect(Collectors.toMap(x -> x.getAirline(), x -> x, (k1, k2) -> k1));
            }

            List<FfpVo> ffpVos = new ArrayList<>();
            for (MbFreshPassengerRelation freshPassenger : mbFreshPassengerRelations) {
                List<MbOrgUserIdcard> cards = Lists.newArrayList();
                FfpVo vo = new FfpVo();
                if (freshPassenger.getEmployeeFlag() == 1) {
                    //如果是本人
                    if (freshPassenger.getFreshUid().equals(uid)) {
                        vo.setIsOwnner(true);
                        vo.setAgentAble(true);
                    }
                    MbOrgEmployeeInfo userInfo = employeeInfoMap.get(freshPassenger.getFreshUid());
                    if (userInfo == null) {
                        continue;
                    }
                    // 是否读取nameInfo的数据,T:读取  F:不读取
                    boolean nameInfoReadSwitch = "T".equalsIgnoreCase(organizationApollo.getNameInfoReadSwitch());
                    if(nameInfoReadSwitch && StrUtil.isNotBlank(userInfo.getNameInfo())){
                        NameInfoBo nameInfoBo = JsonUtils.parse(userInfo.getNameInfo(),NameInfoBo.class);
                        vo.setSurname(nameInfoBo.getSurname());
                        vo.setGivenname(nameInfoBo.getGivenname());
                        vo.setFullEnName(com.corpgovernment.organization.util.StrUtils.processFullEnName(nameInfoBo.getSurname(),nameInfoBo.getGivenname()));
                        vo.setFullName(nameInfoBo.getFullName());
                        vo.setNationality(nameInfoBo.getNationality());
                    }else{
                        vo.setSurname(userInfo.getLastEnName());
                        vo.setGivenname(userInfo.getFirstEnName());
                        vo.setFullEnName(com.corpgovernment.organization.util.StrUtils.processFullEnName(userInfo.getLastEnName(),userInfo.getFirstEnName()));
                        vo.setFullName(userInfo.getName());
                        vo.setNationality(userInfo.getNationality());
                    }
                    //取交集
                    //vo.setAgentAble(false);
                    List<MbUserOrgRelation> retailList = new ArrayList<>();
                    List<MbUserOrgRelation> userOrgRelations = userRelationMap.get(freshPassenger.getUid());
                    retailList.addAll(userOrgRelations == null ? new ArrayList<>() : userOrgRelations);
                    List<String> collect = retailList.stream().map(MbUserOrgRelation::getOrgId).collect(Collectors.toList());
                    collect.retainAll(orgIds);
                    log.info("待定权限查询  当前人组织id:{}  当前匹配到得数据:{} ", JsonUtils.toJsonString(userOrgRelations), JsonUtils.toJsonString(collect));
                    if (!CollectionUtils.isEmpty(collect)) {
                        vo.setAgentAble(Boolean.TRUE);
                    } else {
                        vo.setAgentAble(Boolean.FALSE);
                    }
                    vo.setFirstName(userInfo.getFirstEnName());
                    vo.setLastName(userInfo.getLastEnName());
                    vo.setDepartment(baseUserInfo.getOrgName());
                    vo.setPhoneNum(userInfo.getMobilePhone());
                    vo.setEmail(userInfo.getEmail());
                    String loginPhone = userLoginMap.get(freshPassenger.getUid()).getPhoneNum();
                    //String newLoginPhone = loginPhone.substring(0, 3) + "****" + loginPhone.substring(7);
                    vo.setLoginPhoneNum(loginPhone);
                    String gender = userInfo.getGender();
                    if (DeviceEnum.PC.toString().equalsIgnoreCase(request.getDevice())) {
                        vo.setRoleType(NumberUtils.INTEGER_ONE.toString());
                        vo.setEmail(userInfo.getEmail());
                    } else {
                        vo.setRoleType("员工");
                    }
                    if (StringUtils.isNotBlank(gender)) {
                        vo.setSex(gender.equals(OrgEmployeeConst.MAN) ? "0" : "1");
                    }
                    vo.setBirthday(userInfo.getBirthday());
                    cards = uidCardMapList.get(freshPassenger.getFreshUid());
                    //****************************
                    //封装常旅卡信息,员工
                    List<MbOrgUserFfpinfo> ffpinfos = organizationUserFfpService.listByUid(freshPassenger.getFreshUid());
                    List<FrequentCardListBean> flist = Lists.newArrayList();
                    FrequentPassengerDto frequentPassengerDto = null;
                    for (MbOrgUserFfpinfo ffpinfo : ffpinfos) {
                        if (frequentPassengerDtoMap != null) {
                            frequentPassengerDto = frequentPassengerDtoMap.get(ffpinfo.getAirline());
                        }
                        if (frequentPassengerDto != null) {
                            String cardName = frequentPassengerDto.getAirlineName();
                            String club = frequentPassengerDto.getLabel();
                            String cardId = frequentPassengerDto.getAirline();
                            bean = FrequentCardListBean.builder().cardId(cardId).cardNo(ffpinfo.getFfpno()).cardName(StringUtils.isBlank(cardName) ? club : cardName).club(club).build();
                            flist.add(bean);
                        } else {
                            log.info("调用basic server exception:{}", JsonUtils.toJsonString(jsonResult));
                        }
                    }
                    vo.setFrequentCardList(flist);
                    vo.setFrequentId(freshPassenger.getId());
                    vo.setCountryCode(userInfo.getAreaCode());
                } else if (freshPassenger.getEmployeeFlag() == 0) {
                    cards = nonUidCardMapList.get(Long.valueOf(freshPassenger.getFreshUid()));
                    MbOrgNonEmployeeInfo userNonInfo = nonEmployeeInfoMap.get(Long.valueOf(freshPassenger.getFreshUid()));
                    if (userNonInfo != null) {
                        // 是否读取nameInfo的数据,T:读取  F:不读取
                        boolean nameInfoReadSwitch = "T".equalsIgnoreCase(organizationApollo.getNameInfoReadSwitch());
                        if(nameInfoReadSwitch && StrUtil.isNotBlank(userNonInfo.getNameInfo())){
                            NameInfoBo nameInfoBo = JsonUtils.parse(userNonInfo.getNameInfo(),NameInfoBo.class);
                            vo.setSurname(nameInfoBo.getSurname());
                            vo.setGivenname(nameInfoBo.getGivenname());
                            vo.setFullEnName(com.corpgovernment.organization.util.StrUtils.processFullEnName(nameInfoBo.getSurname(),nameInfoBo.getGivenname()));
                            vo.setFullName(nameInfoBo.getFullName());
                            vo.setNationality(nameInfoBo.getNationality());
                        }else{
                            vo.setSurname(userNonInfo.getLastEnName());
                            vo.setGivenname(userNonInfo.getFirstEnName());
                            vo.setFullEnName(com.corpgovernment.organization.util.StrUtils.processFullEnName(userNonInfo.getLastEnName(),userNonInfo.getFirstEnName()));
                            vo.setFullName(userNonInfo.getName());
                        }
                        vo.setDepartment(userNonInfo.getName());
                        vo.setEmail(userNonInfo.getEmail());
                        if (DeviceEnum.PC.toString().equalsIgnoreCase(request.getDevice())) {
                            vo.setRoleType(NumberUtils.INTEGER_ZERO.toString());
                            vo.setEmail(userNonInfo.getEmail());
                        } else {
                            vo.setRoleType("非员工");
                        }
                        boolean bookForNonEmp = Optional.ofNullable(bookingRange).map(BookingRange::getBookForNonEmp).orElse(false);
                        if (bookForNonEmp) {
                            vo.setAgentAble(Boolean.TRUE);
                        } else {
                            vo.setAgentAble(Boolean.FALSE);
                        }
                        vo.setFirstName(userNonInfo.getFirstEnName());
                        vo.setLastName(userNonInfo.getLastEnName());
                        String mobilePhone = userNonInfo.getMobilePhone();
                        if (StrUtil.isNotBlank(mobilePhone)) {
                            String[] split = mobilePhone.split(" ");
                            if (split.length == 1) {
                                vo.setPhoneNum(split[0]);
                            } else {
                                vo.setCountryCode(split[0]);
                                vo.setPhoneNum(split[1]);
                            }
                        }

                        String gender = userNonInfo.getGender();
                        if (StringUtils.isNotBlank(gender)) {
                            vo.setSex(gender.equals(OrgEmployeeConst.MAN) ? "0" : "1");
                        }
                        vo.setBirthday(userNonInfo.getBirthday());
                        vo.setNationality(userNonInfo.getNationality());

                        //封装常旅卡信息,员工
                        List<MbOrgUserFfpinfo> ffpinfos = organizationUserFfpService.listByNonEmployeeIds(Collections.singletonList(Long.valueOf(freshPassenger.getFreshUid())));
                        List<FrequentCardListBean> flist = Lists.newArrayList();
                        FrequentPassengerDto frequentPassengerDto = null;
                        for (MbOrgUserFfpinfo ffpinfo : ffpinfos) {
                            if (frequentPassengerDtoMap != null) {
                                frequentPassengerDto = frequentPassengerDtoMap.get(ffpinfo.getAirline());
                            }
                            if (frequentPassengerDto != null) {
                                String cardName = frequentPassengerDto.getAirlineName();
                                String club = frequentPassengerDto.getLabel();
                                String cardId = frequentPassengerDto.getAirline();
                                bean = FrequentCardListBean.builder().cardId(cardId).cardNo(ffpinfo.getFfpno()).cardName(StringUtils.isBlank(cardName) ? club : cardName).club(club).build();
                                flist.add(bean);
                            } else {
                                log.info("调用basic server exception:{}", JsonUtils.toJsonString(jsonResult));
                            }
                        }
                        vo.setFrequentCardList(flist);
                        vo.setFrequentId(freshPassenger.getId());
                    }
                }
                // 封装证件信息
                if (CollectionUtils.isNotEmpty(cards)) {
                    Map<Integer, CardDetailVo> cardDetailVo = packageCardDetailVo(cards);
                    vo.setCardList(cardDetailVo);
                } else {
                    vo.setCardList(map);
                }
                ffpVos.add(vo);
            }
            ffpPageVo.setTotalPage(totalPage);
            ffpPageVo.setTotalCount(totalCount);
            ffpPageVo.setPageNo(pageInfo.getCurrent());
            ffpPageVo.setPageSize(pageInfo.getSize());
            ffpPageVo.setPlist(ffpVos);
            ffpPageVo.setBookForNonEmp(Optional.ofNullable(bookingRange).map(BookingRange::getBookForNonEmp).orElse(false));
            return JSONResult.success(ffpPageVo);
        } catch (Exception e){
            log.error("{}", e);
        } finally {
            log.info("{}", logContext);
        }
        return JSONResult.ok();
    }


    /**
     * 删除常旅信息
     *
     * @param ffpIdRequest
     * @return
     */
    @Override
    @Transactional
    public JSONResult deleteFfpItem(FfpIdRequest ffpIdRequest) {
        if (ffpIdRequest == null || ffpIdRequest.getFrequentId() == null) {
            throw new CommonException(3000, "删除常旅信息请求参数为空！");
        }
        //查询关联
        MbFreshPassengerRelation mbFreshPassengerRelation = freshPassengerRelationService.selectByPk(ffpIdRequest.getFrequentId());
        if (mbFreshPassengerRelation == null) {
            throw new CommonException(3000, "数据不存在");
        }
        //删除fresh表 nonemployee表 相关记录
        if (mbFreshPassengerRelation.getEmployeeFlag() != null && mbFreshPassengerRelation.getEmployeeFlag() == 0) {
            Long nonEmployeeUid = Long.valueOf(mbFreshPassengerRelation.getFreshUid());
            freshPassengerService.deleteNonEmployee(nonEmployeeUid);
            deleteOperateLog(String.valueOf(nonEmployeeUid));
            mbOrgNonEmployeeMapper.deleteByPrimaryKey(nonEmployeeUid);

            organizationUserFfpService.deleteByNonEmployeeUid(nonEmployeeUid);

            organizationUserIdCardService.deleteByNonEmployeeUid(nonEmployeeUid);
        }
        //删除常旅关联
        freshPassengerRelationService.deletedRelation(mbFreshPassengerRelation.getUid(), mbFreshPassengerRelation.getFreshUid());
//          freshPassengerService.deleteFreshPasssengerById(ffpIdRequest.getFrequentId());
//            deleteOperateLog(String.valueOf(ffpIdRequest.getFrequentId()));
        deleteOperateLog(mbFreshPassengerRelation.getFreshUid());
        return JSONResult.ok();
    }


    private void listDirectDepartmentIdsByCompanyId(String
                                                            recentCompanyId, Map<String, List<MbOrgInfo>> parentIdMapList, List<String> departmentIds) {
        List<MbOrgInfo> mbOrgInfoList = parentIdMapList.get(recentCompanyId);
        if (CollectionUtils.isNotEmpty(mbOrgInfoList)) {
            for (MbOrgInfo mbOrgInfo : mbOrgInfoList) {
                if (mbOrgInfo.getOrgType().equals(OrganizationConst.DEPARTMENT)) {
                    departmentIds.add(mbOrgInfo.getOrgId());
                    listAllDepartmentIdsByCompanyId(mbOrgInfo.getOrgId(), parentIdMapList, departmentIds);
                }
            }
        }
    }

    private List<CardVo> packageCardVo(List<MbOrgUserIdcard> cards) {
        List<CardVo> cardVoList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(cards)) {
            for (MbOrgUserIdcard card : cards) {
                // 过滤掉学生证
                if (CardCodeEnum.STUDENT_CARD.getCode().equals(card.getCardType().toString()) ||
                        CardCodeEnum.SAILOR_CARD.getCode().equals(card.getCardType().toString()) ||
                        CardCodeEnum.FOREIGNER_CARD.getCode().equals(card.getCardType().toString())) {
                    continue;
                }
                CardVo cardVo = new CardVo();
                cardVo.setValue(card.getCardNo());
                cardVo.setType(card.getCardType());
                cardVo.setValidity(card.getTimeLimit());
                cardVo.setName(CardTypeSwitchUtil.getNameById(card.getCardType()));
                cardVoList.add(cardVo);
            }
        }
        return cardVoList;
    }

    private Map<Integer, CardDetailVo> packageCardDetailVo(List<MbOrgUserIdcard> cards) {
//        List<CardDetailVo> cardVoList = new ArrayList<>();
//         List<Map<Integer,CardDetailVo>> cardList =new ArrayList<>();
        Map<Integer, CardDetailVo> map = new HashMap<>();
        if (CollectionUtils.isNotEmpty(cards)) {
            for (MbOrgUserIdcard card : cards) {

                // 过滤掉学生证
                if (CardCodeEnum.STUDENT_CARD.getCode().equals(card.getCardType().toString()) ||
                        CardCodeEnum.SAILOR_CARD.getCode().equals(card.getCardType().toString()) ||
                        CardCodeEnum.FOREIGNER_CARD.getCode().equals(card.getCardType().toString())) {
                    continue;
                }
                CardDetailVo detailVo = new CardDetailVo();
                detailVo.setCardId(card.getCardNo());
                detailVo.setValidDate(DateUtil.dateToString(card.getTimeLimit(), "yyyy-MM-dd"));
                detailVo.setCardType(card.getCardType());
                //判断证件时效
                detailVo.setCardStatus(checkCardIsExpired(card));
                detailVo.setPlaceOfIssue(card.getPlaceOfIssue());

                map.put(detailVo.getCardType(), detailVo);
            }
        }
        return map;
    }

    private CardDetailVo cardDetail(List<MbOrgUserIdcard> cards) {
        Map<Integer, CardDetailVo> map = new TreeMap<>();
        if (CollectionUtils.isNotEmpty(cards)) {
            CardDetailVo detailVo;
            for (MbOrgUserIdcard card : cards) {
                // 过滤掉不需要的证件
                if (CardCodeEnum.STUDENT_CARD.getCode().equals(card.getCardType().toString())
                        || CardCodeEnum.TRAVEL_CARD.getCode().equals(card.getCardType().toString())
                        || CardCodeEnum.FOREIGNER_LIVE_CARD.getCode().equals(card.getCardType().toString())
                        || CardCodeEnum.GANGAO_LIVE_CARD.getCode().equals(card.getCardType().toString())
                        || CardCodeEnum.BOOKLET.getCode().equals(card.getCardType().toString())
                        || CardCodeEnum.BIRTH_CERTIFICATE.getCode().equals(card.getCardType().toString())) {
                    continue;
                }
                detailVo = new CardDetailVo();
                detailVo.setCardId(card.getCardNo());
                detailVo.setValidDate(DateUtil.dateToString(card.getTimeLimit(), "yyyy-MM-dd"));
                detailVo.setCardType(card.getCardType());
                //判断证件时效
                detailVo.setCardStatus(checkCardIsExpired(card));
                map.put(detailVo.getCardType(), detailVo);
            }
        }
        CardDetailVo cardDetailVos = null;
        if (MapUtils.isNotEmpty(map)) {
            for (Map.Entry<Integer, CardDetailVo> m : map.entrySet()) {
                cardDetailVos = m.getValue();
                break;
            }
        }

        return cardDetailVos == null ? new CardDetailVo() : cardDetailVos;
    }


    private Integer checkCardIsExpired(MbOrgUserIdcard card) {

        //过期时间
        Date timeLimit = card.getTimeLimit();
        if (timeLimit == null) {
            return 0;
        }
        String timeStr = DateUtil.dateToYMD(timeLimit) + " 23:59:59";
        timeLimit = DateUtil.stringToDate(timeStr, DF_YMD_HMS);
        log.info("证件比较时的过期时间为：{}",timeLimit);
        //当前时间
        Calendar now = Calendar.getInstance();
        //过期时间
        Calendar c1 = Calendar.getInstance();
        c1.setTime(timeLimit);//过期日期

        Calendar c2 = Calendar.getInstance();
        //当前时间六个月后的时间
        c2.add(Calendar.DATE, 180);

        int i = c1.compareTo(c2);
        int j = c1.compareTo(now);
        return i >= 0 ? 0 : (j > 0) ? 1 : 2;
    }


    private MobilePhoneVo packageMobilePhoneVo(String mobilePhone) {
        MobilePhoneVo mobilePhoneVo = new MobilePhoneVo();
        if (StringUtils.isNotBlank(mobilePhone)) {
            String[] s = mobilePhone.split(" ");
            String countryCode = s[0];
            String phone = s[1];
            // 国家码去除“+”号
            if (StringUtils.isNotBlank(countryCode)) {
                countryCode = countryCode.replace("+", "");
            }
            mobilePhoneVo.setCountryCode(countryCode);
            mobilePhoneVo.setValue(phone);
        }
        return mobilePhoneVo;
    }

    public static String findRecentCompanyId(String orgId, Map<String, MbOrgInfo> orgIdMap) {
        // 查询
        MbOrgInfo mbOrgInfo = orgIdMap.get(orgId);
        if (mbOrgInfo == null) {
            return null;
        }
        if (mbOrgInfo.getOrgType().equals(OrganizationConst.DEPARTMENT)) {
            return findRecentCompanyId(mbOrgInfo.getParentId(), orgIdMap);
        } else {
            return mbOrgInfo.getOrgId();
        }
    }

    public static String findFirstCompanyId(String orgId, Map<String, MbOrgInfo> orgIdMap) {
        // 查询
        MbOrgInfo mbOrgInfo = orgIdMap.get(orgId);
        if (mbOrgInfo == null) {
            return null;
        }
        if (StringUtils.isNotBlank(mbOrgInfo.getParentId())){
            return findFirstCompanyId(mbOrgInfo.getParentId(), orgIdMap);
        }else{
            return orgId;
        }
    }

    private void listAllDepartmentIdsByCompanyId(String parentId, Map<String, List<MbOrgInfo>> parentIdMapList, List<String> departmentIds) {
        List<MbOrgInfo> mbOrgInfoList = parentIdMapList.get(parentId);
        if (CollectionUtils.isNotEmpty(mbOrgInfoList)) {
            for (MbOrgInfo mbOrgInfo : mbOrgInfoList) {
                if (mbOrgInfo.getOrgType().equals(OrganizationConst.DEPARTMENT)) {
                    departmentIds.add(mbOrgInfo.getOrgId());
                    listAllDepartmentIdsByCompanyId(mbOrgInfo.getOrgId(), parentIdMapList, departmentIds);
                }
            }
        }
    }

    private void listAllOrgIdsByCompanyId(String parentId, Map<String, List<MbOrgInfo>> parentIdMapList, List<String> departmentIds) {
        List<MbOrgInfo> mbOrgInfoList = parentIdMapList.get(parentId);
        if (CollectionUtils.isNotEmpty(mbOrgInfoList)) {
            for (MbOrgInfo mbOrgInfo : mbOrgInfoList) {
                departmentIds.add(mbOrgInfo.getOrgId());
                listAllOrgIdsByCompanyId(mbOrgInfo.getOrgId(), parentIdMapList, departmentIds);
            }
        }
    }

    private void listAllDepartmentIdsByCompanyId(String parentId, Map<String, List<MbOrgInfo>> parentIdMapList, List<String> departmentIds,Boolean isErgodic) {
        List<MbOrgInfo> mbOrgInfoList = parentIdMapList.get(parentId);
        if (CollectionUtils.isNotEmpty(mbOrgInfoList)) {
            for (MbOrgInfo mbOrgInfo : mbOrgInfoList) {
                // 部门信息查询，是否要穿透查询子公司信息
                if (mbOrgInfo.getOrgType().equals(OrganizationConst.DEPARTMENT) || (isErgodic
                        && OrganizationConst.COMPANY.equals(mbOrgInfo.getOrgType()))) {
                    departmentIds.add(mbOrgInfo.getOrgId());
                    listAllDepartmentIdsByCompanyId(mbOrgInfo.getOrgId(), parentIdMapList, departmentIds, isErgodic);
                }
            }
        }
    }

    @Override
    public List<MbOrgInfo> findFirstLevelChildrenDepartmentByOrgId(String orgId, String name) {
        MbOrgInfo queryParam = new MbOrgInfo();
        queryParam.setParentId(orgId);
        queryParam.setOrgType(OrgTypeEnum.D.getCode());
        queryParam.setDeleteTime(new Date(0));
        List<MbOrgInfo> orgList = mbOrgInfoMapper.select(queryParam);
        if (CollectionUtils.isEmpty(orgList)) {
            return new ArrayList<>();
        }
        return orgList.stream()
                .filter(e -> StringUtils.isNotBlank(e.getName()) && (StringUtils.isEmpty(name) || e.getName().contains(name)))
                .collect(Collectors.toList());
    }
    @Override
    public List<MbOrgInfo> findMbOrgInfoByOrgId(String orgId, String name) {
        MbOrgInfo queryParam = new MbOrgInfo();
        queryParam.setParentId(orgId);
        queryParam.setDeleteTime(new Date(0));
        List<MbOrgInfo> orgList = mbOrgInfoMapper.select(queryParam);
        if (CollectionUtils.isEmpty(orgList)) {
            return new ArrayList<>();
        }
        return orgList.stream()
                .filter(e -> StringUtils.isNotBlank(e.getName()) && (StringUtils.isEmpty(name) || e.getName().contains(name)))
                .collect(Collectors.toList());
    }
    public List<String> queryListRecentCompanyAllDepartmentByOrgId(String orgId) {
        List<MbOrgInfo> mbOrgInfoList = mbOrgInfoMapper.listAll();
        Map<String, MbOrgInfo> orgIdMap = mbOrgInfoList.stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, mbOrgInfo -> mbOrgInfo));
        Map<String, List<MbOrgInfo>> parentIdMapList = mbOrgInfoList.stream().filter(mbOrgInfo -> StringUtils.isNotBlank(mbOrgInfo.getParentId())).collect(Collectors.groupingBy(MbOrgInfo::getParentId));
        String recentCompanyId = findRecentCompanyId(orgId, orgIdMap);
        List<String> departmentIds = new ArrayList<>();
        listAllDepartmentIdsByCompanyId(recentCompanyId, parentIdMapList, departmentIds);
        return departmentIds;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JSONResult saveFfpItem(FfpAddRequest ffpAddRequest, BaseUserInfo baseUserInfo) {
        ObjectStringTrimUtils.allFieldRemoveWarp(ffpAddRequest);
        log.info("saveFfpItem :{}", ffpAddRequest);
        //新增非员工信息，freshpassenger表，noemploy表
        FfpExtendsFfpModifyRequest ffpExtendsFfpModifyRequest = JsonUtils.convert(ffpAddRequest, FfpExtendsFfpModifyRequest.class);
        //校验参数
        validateSaveOrUpdateParams(ffpExtendsFfpModifyRequest);
        //校验证件类型
        List<FfpAddRequest.CardInfo> cardIdList = ffpAddRequest.getCardIdList();

        //部分证件号码转大写
        if (CollectionUtils.isNotEmpty(ffpAddRequest.getCardIdList())){
            ffpAddRequest.getCardIdList().forEach(e ->{
                if (CardEnum.needUpperCaseCard(e.getCardType().toString())){
                    e.setCardId(e.getCardId().toUpperCase());
                }
            });
        }

        Example passengerRelationExample = new Example(MbFreshPassengerRelation.class);
        passengerRelationExample.createCriteria().andEqualTo("uid", baseUserInfo.getUid());
        List<MbFreshPassengerRelation> mbFreshPassengerRelations = mbFreshPassengerRelationMapper.selectByExample(passengerRelationExample);

        List<String> freshUidList = mbFreshPassengerRelations.stream().filter(item -> Objects.nonNull(item)).map(MbFreshPassengerRelation::getFreshUid).collect(Collectors.toList());

        Example userIdcardExample = new Example(MbOrgUserIdcard.class);
        userIdcardExample.createCriteria().orIn("employeeUid", freshUidList).orIn("nonEmployeeId", freshUidList).andEqualTo("deleteTime", "1970-01-01 08:00:00.000");
        List<MbOrgUserIdcard> mbOrgUserIdcards = mbOrgUserIdcardMapper.selectByExample(userIdcardExample);

//        List<String> idCardList = mbOrgUserIdcards.stream().filter(item -> Objects.nonNull(item)).map(item -> {
//            return item.getCardType()+"_"+EncryptUtils.sm4Decrypt(item.getCardNo());
//        }).collect(Collectors.toList());
//
//        if (CollUtil.isNotEmpty(cardIdList)) {
//            for (FfpAddRequest.CardInfo cardInfo : cardIdList) {
////                List<MbOrgUserIdcard> list = organizationUserIdCardService.listEmployeeByTypeAndNo(cardInfo.getCardType(), cardInfo.getCardId());
////                if (!CollectionUtils.isEmpty(list)) {
////                    throwCommonException("该证件号不可重复");
////                }
//                if (idCardList.contains(cardInfo.getCardType() + "_" + cardInfo.getCardId())){
//                    throw new CommonException("该证件号不可重复");
//                }
//            }
//        }
        //校验航空公司
        List<FrequentCardListBean> frequentCardsList = ffpAddRequest.getFrequentCardsList();
        Map<String, Integer> map = Maps.newHashMap();
        if (!CollectionUtils.isEmpty(frequentCardsList)) {
            for (int i = 0; i < frequentCardsList.size(); i++) {
                if (!RegularUtils.isNumer(frequentCardsList.get(i).getCardNo())) {
                    throw new CorpBusinessException(OrganizationResponseCodeEnum.CARD_NO_ERROR);
                }
                if (map.containsKey(frequentCardsList.get(i).getCardNo())) {
                    map.put(frequentCardsList.get(i).getCardNo(), map.get(frequentCardsList.get(i).getCardNo()) + 1);
                } else {
                    map.put(frequentCardsList.get(i).getCardNo(), 1);
                }
            }
        }

        if (map != null && map.size() > 0) {
            for (Map.Entry<String, Integer> entry : map.entrySet()) {
                int value = entry.getValue();
                if (value > 1) {
                    throw new CorpBusinessException(OrganizationResponseCodeEnum.CARD_NO_EXISTS);
                }
            }
        }

        //组装参数
        MbOrgNonEmployeeInfo info = new MbOrgNonEmployeeInfo();
        NameInfoBo nameInfoBo = JsonUtils.parse(JsonUtils.toJsonString(ffpAddRequest),NameInfoBo.class);
        nameInfoBo.setFullEnName(com.corpgovernment.organization.util.StrUtils.processFullEnName(nameInfoBo.getSurname(),nameInfoBo.getGivenname()));
        if(StrUtils.checkNameInfo(nameInfoBo)){
            info.setNameInfo(JsonUtils.toJsonString(nameInfoBo));
        }
        if(StringUtils.isNotBlank(ffpAddRequest.getFirstName()) && StringUtils.isNotBlank(ffpAddRequest.getLastName())){
            info.setFirstEnName(ffpAddRequest.getFirstName());
            info.setLastEnName(ffpAddRequest.getLastName());
        } else if(StringUtils.isNotBlank(ffpAddRequest.getSurname()) && StringUtils.isNotBlank(ffpAddRequest.getGivenname())){
            info.setFirstEnName(ffpAddRequest.getGivenname());
            info.setLastEnName(ffpAddRequest.getSurname());
        }else{
            log.error("firstName,lastName error:{},{},{},{}",
                    ffpAddRequest.getFirstName() ,ffpAddRequest.getLastName(),ffpAddRequest.getSurname() ,ffpAddRequest.getGivenname());
        }
        info.setBirthday(DateUtil.stringToDate(ffpAddRequest.getBirthday(), DateUtil.DF_YMD));
        if (ffpAddRequest.getSex() != null) {
            String gender = ffpAddRequest.getSex().equals(0) ? "M" : "F";
            info.setGender(gender);
        }
        info.setNationality(ffpAddRequest.getNationality());
        if (DeviceEnum.PC.toString().equals(ffpAddRequest.getDevice())) {
            info.setMobilePhone("+86 " + ffpAddRequest.getPhoneNum());
        } else {
            if (StringUtils.isNotBlank(ffpAddRequest.getCountryCode())) {
                info.setMobilePhone(ffpAddRequest.getCountryCode() + " " + ffpAddRequest.getPhoneNum());
            } else {
                info.setMobilePhone(ffpAddRequest.getPhoneNum());
            }
        }

        info.setEmployeeUid(baseUserInfo.getUid());
        info.setName(ffpAddRequest.getFullName());
        //----------------start 2019-08-16 16:31 罗江新加字段email---------------------
        info.setEmail(ffpAddRequest.getEmail());
        //----------------end---------------------
        //写库非员工表
        mbOrgNonEmployeeMapper.insertSelective(info);
//        insertOperateLog(info);

        MbFreshPassenger param = new MbFreshPassenger();
        param.setNonEmployeeUid(info.getId());
        param.setCreateUid(baseUserInfo.getUid());
        param.setName(ffpAddRequest.getFullName());
        param.setEnName(ffpAddRequest.getFirstName() + "/" + ffpAddRequest.getLastName());
        freshPassengerService.save(param);
//        insertOperateLog(param);
        //写库 身份证件id
        if (CollectionUtils.isNotEmpty(cardIdList)) {
            List<MbOrgUserIdcard> addCardTypes = cardIdList.stream().filter(Objects::nonNull).map(ct -> {
                MbOrgUserIdcard temp = new MbOrgUserIdcard();
                temp.setCardType(ct.getCardType());
                temp.setCardNo(ct.getCardId());
                temp.setTimeLimit(StringUtils.isEmpty(ct.getValidDate()) ? null : DateUtil.stringToDate(ct.getValidDate(), DateUtil.DF_YMD));
                temp.setNonEmployeeId(info.getId());
                return temp;
            }).collect(Collectors.toList());
            organizationUserIdCardService.batchSave(addCardTypes);
        }

        //写库常旅客卡表
        if (CollectionUtils.isNotEmpty(frequentCardsList)) {
            MbOrgUserFfpinfo ffpinfo;
            for (FrequentCardListBean bean : frequentCardsList) {
                ffpinfo = new MbOrgUserFfpinfo();
                ffpinfo.setNonEmployeeUid(info.getId());
                ffpinfo.setAirline(bean.getCardId());
                ffpinfo.setFfpno(bean.getCardNo());
                ffpinfo.setIsDeleted(false);
                organizationUserFfpService.save(ffpinfo);
//                insertOperateLog(ffpinfo);
            }
        }
        //插入常旅关联表
        MbFreshPassengerRelation freshPassengerRelation = new MbFreshPassengerRelation();
        freshPassengerRelation.setIsDeleted(false);
        freshPassengerRelation.setUid(baseUserInfo.getUid());
        freshPassengerRelation.setFreshTime(new Date());
        freshPassengerRelation.setEmployeeFlag(0);
        freshPassengerRelation.setFreshUid(String.valueOf(info.getId()));
        freshPassengerRelationService.save(freshPassengerRelation);
        return JSONResult.ok();
    }


    /**
     * 新增修改参数校验
     *
     * @param saveOrUpdateRequest
     */
    public void validateSaveOrUpdateParams(FfpExtendsFfpModifyRequest saveOrUpdateRequest) {
        String phoneNum = saveOrUpdateRequest.getPhoneNum();
        if (StringUtils.isBlank(phoneNum)) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.EMPLOYEE_PHONE_NO_EXIST);
        }
        String fullName = saveOrUpdateRequest.getFullName();
        String firstName = saveOrUpdateRequest.getFirstName();
        String lastName = saveOrUpdateRequest.getLastName();
        if (StringUtils.isBlank(fullName) && (StringUtils.isBlank(firstName) || StringUtils.isBlank(lastName))) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.CHINESE_OR_ENGLISH_NAME);
        }
        String email = saveOrUpdateRequest.getEmail();
        if (StringUtils.isNotBlank(email) && !desensitized(email)) {
            boolean isEmail = RegularUtils.isEmail(email);
            if (!isEmail) {
                throw new CorpBusinessException(OrganizationResponseCodeEnum.CONTRACT_EMAIL_FORMAT_ERROR);
            }
        }

        List<FfpAddRequest.CardInfo> cardIdList = saveOrUpdateRequest.getCardIdList();
        List<Integer> cardTypeList = CollUtil.newArrayList();
        if (CollUtil.isNotEmpty(cardIdList)) {
            for (FfpAddRequest.CardInfo cardInfo : cardIdList) {
                if (desensitized(cardInfo.getCardId())) {
                    continue;
                }
                UserCardValidationInfoReqVo userCardValidationInfoReqVo =
                        userCardInfoConvert.cardInfoConvertToUserCardValidationInfo(cardInfo);
                CardValidateUtil.validateUserCard(userCardValidationInfoReqVo);
                cardTypeList.add(cardInfo.getCardType());
            }
        }


        String device = saveOrUpdateRequest.getDevice();
        String nationality = saveOrUpdateRequest.getNationality();
        String birthdayStr = saveOrUpdateRequest.getBirthday();
        Date birthday = DateUtil.stringToDate(birthdayStr, DateUtil.DF_YMD);

        //app除了身份证跟军人证都有国籍，pc国籍必填
        if (DeviceEnum.PC.toString().equalsIgnoreCase(device)) {
            if (StringUtils.isBlank(nationality)) {
                throw new CorpBusinessException(OrganizationResponseCodeEnum.NATIONALITY_IS_NULL);
            }
            if (birthday == null) {
                throw new CorpBusinessException(OrganizationResponseCodeEnum.BIRTHDAY_IS_NULL);
            }
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 59);
            calendar.add(Calendar.DATE, 1);
            if (birthday.after(calendar.getTime())) {
                throw new CorpBusinessException(OrganizationResponseCodeEnum.BIRTHDAY_ERROR);
            }
        } else {
            if (CollUtil.isNotEmpty(cardTypeList) && !cardTypeList.contains(Integer.valueOf(CardCodeEnum.ID_CARD.getCode()))
                    && !cardTypeList.contains(Integer.valueOf(CardCodeEnum.SOLDIER_CARD.getCode()))) {
                if (birthday == null) {
                    throw new CorpBusinessException(OrganizationResponseCodeEnum.BIRTHDAY_IS_NULL);
                }
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 59);
                calendar.add(Calendar.DATE, 1);
                if (birthday.after(calendar.getTime())) {
                    throw new CorpBusinessException(OrganizationResponseCodeEnum.BIRTHDAY_ERROR);
                }
                if (StringUtils.isBlank(nationality)) {
                    throw new CorpBusinessException(OrganizationResponseCodeEnum.NATIONALITY_IS_NULL);
                }
            }
        }

        if (CollectionUtils.isNotEmpty(saveOrUpdateRequest.getFrequentCardsList())){
            for (FrequentCardListBean cardListBean:saveOrUpdateRequest.getFrequentCardsList()){
                if (StringUtils.isBlank(cardListBean.getCardId())){
                    throw new CorpBusinessException(OrganizationResponseCodeEnum.FREQUENT_CARD_ID_NULL);
                }
                if (StringUtils.isBlank(cardListBean.getCardNo())){
                    throw new CorpBusinessException(OrganizationResponseCodeEnum.FREQUENT_CARD_NO_NULL);
                }
            }
        }

    }

    /**
     * 判断数据是否携带脱敏标记
     * @param word
     * @return
     */
    private boolean desensitized(String word) {
        if (StringUtils.isBlank(word)) {
            return false;
        }
        return DesensitizationUtils.isDesensitized(word);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONResult modifyFfpItem(FfpModifyRequest ffpModifyRequest, BaseUserInfo baseUserInfo) {
        // 清除字符串空格
        //ObjectStringTrimUtils.allFieldRemoveWarp(ffpModifyRequest);

        Long frequentId = ffpModifyRequest.getFrequentId();
        String uId = baseUserInfo.getUid();
        if (StringUtils.isBlank(uId)) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.UID_IS_NULL);
        }
        FfpExtendsFfpModifyRequest ffpExtendsFfpModifyRequest = JsonUtils.convert(ffpModifyRequest, FfpExtendsFfpModifyRequest.class);
        ffpExtendsFfpModifyRequest.setCardIdList(ffpModifyRequest.getCardIdList());
        //校验参数
        validateSaveOrUpdateParams(ffpExtendsFfpModifyRequest);
        //查询关联信息
        MbFreshPassengerRelation mbFreshPassengerRelation = freshPassengerRelationService.selectByPk(frequentId);

        //部分证件号码转大写
        if (CollectionUtils.isNotEmpty(ffpModifyRequest.getCardIdList())){
            ffpModifyRequest.getCardIdList().forEach(e ->{
                if (CardEnum.needUpperCaseCard(e.getCardType().toString())){
                    e.setCardId(e.getCardId().toUpperCase());
                }
            });
        }

        //校验证件类型
        if (mbFreshPassengerRelation.getEmployeeFlag() == 1 && uId.equals(mbFreshPassengerRelation.getFreshUid())) {
            //组装参数
            MbOrgEmployeeInfo result = organizationEmployeeService.findByUid(uId);
            if (result == null) {
                throw new CorpBusinessException(OrganizationResponseCodeEnum.EMPLOYEE_INFO_NULL);
            }

            MbOrgEmployeeInfo record = new MbOrgEmployeeInfo();
            record.setAreaCode(ffpModifyRequest.getCountryCode());
            record.setMobilePhone(ffpModifyRequest.getPhoneNum());
            record.setIsBackground(false);
            MbOrgEmployeeInfo byPhone = mbOrgEmployeeLoader.selectOneByRecord(record);
            if (byPhone !=null && !byPhone.getUid().equals(uId)){
                throw new CorpBusinessException(OrganizationResponseCodeEnum.PHONE_EXISTS);
            }

            MbOrgEmployeeInfo info = result;
            if(StringUtils.isNotBlank(ffpModifyRequest.getFirstName()) && StringUtils.isNotBlank(ffpModifyRequest.getLastName())){
                info.setFirstEnName(ffpModifyRequest.getFirstName());
                info.setLastEnName(ffpModifyRequest.getLastName());
            } else if(StringUtils.isNotBlank(ffpModifyRequest.getSurname()) && StringUtils.isNotBlank(ffpModifyRequest.getGivenname())){
                info.setFirstEnName(ffpModifyRequest.getGivenname());
                info.setLastEnName(ffpModifyRequest.getSurname());
            }else{
                log.error("firstName,lastName error:{},{},{},{}",
                        ffpModifyRequest.getFirstName() ,ffpModifyRequest.getLastName(),ffpModifyRequest.getSurname() ,ffpModifyRequest.getGivenname());
            }
            info.setBirthday(Date.from(ZonedDateTime.of(LocalDate.parse(ffpModifyRequest.getBirthday(), DateTimeFormatter.ofPattern(DateUtil.DF_YMD)), LocalTime.MIN, ZoneId.of("GMT+8")).toInstant()));
	        if (ffpModifyRequest.getSex() != null) {
		        String gender = ffpModifyRequest.getSex().equals(0) ? "M" : "F";
		        info.setGender(gender);
	        }
	        info.setNationality(ffpModifyRequest.getNationality());
	        info.setMobilePhone(ffpModifyRequest.getPhoneNum());
	        info.setAreaCode(ffpModifyRequest.getCountryCode());
	        info.setEmail(ffpModifyRequest.getEmail());
	        info.setName(ffpModifyRequest.getFullName());
            NameInfoBo nameInfoBo = JsonUtils.parse(JsonUtils.toJsonString(ffpModifyRequest),NameInfoBo.class);
            nameInfoBo.setFullEnName(com.corpgovernment.organization.util.StrUtils.processFullEnName(nameInfoBo.getSurname(),nameInfoBo.getGivenname()));
            if(StrUtils.checkNameInfo(nameInfoBo)){
                info.setNameInfo(JsonUtils.toJsonString(nameInfoBo));
            }
	        //更新员工表
	        organizationEmployeeService.updateEmployeeSelective(info);
	        //更新mb_user_info
	        MbUserLoginVo mbUserLoginVo = new MbUserLoginVo();
	        mbUserLoginVo.setUid(baseUserInfo.getUid());
	        mbUserLoginVo.setUserName(ffpModifyRequest.getFullName());
	        mbUserLoginVo.setPhoneNum(ffpModifyRequest.getPhoneNum());
	        mbUserLoginVo.setCountryCode(ffpModifyRequest.getCountryCode());
	        mbUserLoginVo.setCardNo(ffpModifyRequest.getCardIdList().get(0).getCardId());
	        this.updateUserLogin(mbUserLoginVo);
	        //更新freshpassenger
	        MbFreshPassenger mbFreshPassenger = new MbFreshPassenger();
	        mbFreshPassenger.setEmployeeUid(uId);
	        mbFreshPassenger.setName(ffpModifyRequest.getFullName());
	        mbFreshPassenger.setEnName(ffpModifyRequest.getFirstName() + "/" + ffpModifyRequest.getLastName());
	        freshPassengerService.updateByEmployeeId(mbFreshPassenger);
	        //更新身份证件
	        //优先校验证件唯一性
	        List<CardInfo> cardIdList = ffpModifyRequest.getCardIdList();
	        // 先删除用户证件，然后再插入现有证件
	        //boolean b1 = organizationUserIdCardService.deleteByEmployeeUid(uId);
            List<MbOrgUserIdcard> existCardList = organizationUserIdCardService.findByEmployeeUid(uId);
            List<MbOrgUserIdcard> needDeleteCardList = existCardList.stream().filter(e -> checkDeleteCard(e, cardIdList)).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(needDeleteCardList)){
                organizationUserIdCardService.deleteByList(needDeleteCardList);
            }
            if (CollectionUtils.isNotEmpty(cardIdList)) {
		        for (CardInfo userIdCardFrontVo : cardIdList) {
			        // 判断证件信息是否已经存在
			        List<MbOrgUserIdcard> mbOrgUserIdcardList = organizationUserIdCardService.findByTypeAndNo(userIdCardFrontVo.getCardType(), userIdCardFrontVo.getCardId(), false);
			        for (MbOrgUserIdcard mbOrgUserIdcard : mbOrgUserIdcardList) {
				        if (!StrUtil.equals(mbOrgUserIdcard.getEmployeeUid(), uId)) {
					        throw new CorpBusinessException(OrganizationResponseCodeEnum.CARD_TYPE_EXISTS, Optional.ofNullable(CardTypeEnum.getByCode(userIdCardFrontVo.getCardType())).map(CardTypeEnum::getDesc).orElse(CardTypeEnum.UNKNOWN.getDesc()), userIdCardFrontVo.getCardId());
				        }
			        }
			        // 保存
			        MbOrgUserIdcard mbOrgUserIdcard = new MbOrgUserIdcard();
			        mbOrgUserIdcard.setCardType(userIdCardFrontVo.getCardType());
			        mbOrgUserIdcard.setCardNo(userIdCardFrontVo.getCardId());
			        if (StrUtil.isNotBlank(userIdCardFrontVo.getValidDate())) {
				        mbOrgUserIdcard.setTimeLimit(DateUtil.stringToDate(userIdCardFrontVo.getValidDate(), DateUtil.DF_YMD));
			        }
                    mbOrgUserIdcard.setPlaceOfIssue(userIdCardFrontVo.getPlaceOfIssue());
			        mbOrgUserIdcard.setEmployeeUid(uId);
                    // 判断用户是否存在该类型证件
                    MbOrgUserIdcard byEmployeeUidAndType = organizationUserIdCardService.findByEmployeeUidAndType(mbOrgUserIdcard.getEmployeeUid(), mbOrgUserIdcard.getCardType());
                    if (byEmployeeUidAndType == null) {
                        // 不存在，则插入
                        log.info("Insert when cardType: {} not exists", mbOrgUserIdcard.getCardType());
                        organizationUserIdCardService.save(mbOrgUserIdcard);
                    } else {
                        // 存在，则更新
                        organizationUserIdCardService.updateEmployeeCard(mbOrgUserIdcard);
                    }
		        }
	        }

            List<FrequentCardListBean> frequentCardsList = ffpModifyRequest.getFrequentCardsList();
            // 为空,就删除用户所有常旅客卡
            organizationUserFfpService.deleteByUid(mbFreshPassengerRelation.getFreshUid());
            if (CollectionUtils.isNotEmpty(frequentCardsList)) {
                // 判断航司是否重复
                boolean hasDuplicateCardId = frequentCardsList.stream()
                        .collect(Collectors.groupingBy(FrequentCardListBean::getCardId))
                        .values().stream()
                        .filter(group -> group.size() > 1)
                        .anyMatch(group -> true);
                if(hasDuplicateCardId){
                    throw new CorpBusinessException(ExceptionCodeEnum.Alert, "同一航司只能保存一张会员卡.");
                }

                Map<String, List<FrequentCardListBean>> cardMap = frequentCardsList.stream().collect(Collectors.groupingBy(FrequentCardListBean::getCardNo));

                cardMap.forEach((key, cardList) ->{
                    if (cardList.size() > 1){
                        StringBuilder cardLogContent = new StringBuilder();
                        cardLogContent.append("常旅卡号重复：");
                        for (FrequentCardListBean cardInfo:cardList){
                            cardLogContent.append(cardInfo.getCardName()).append(",");
                        }
                        if (cardLogContent.lastIndexOf(",") > 0){
                            cardLogContent.deleteCharAt(cardLogContent.length()-1);
                        }
                        throw new CorpBusinessException(ExceptionCodeEnum.Alert, cardLogContent.toString());
                    }
                });

                //更新常旅客卡
                frequentCardsList.forEach(i -> {
                    MbOrgUserFfpinfo param = new MbOrgUserFfpinfo();
                    param.setUid(baseUserInfo.getUid());
                    param.setAirline(i.getCardId());
                    param.setFfpno(i.getCardNo());
                    organizationUserFfpService.save(param);
                });
            }
        }  else {
            //更新非员工信息
            //组装参数
            MbOrgNonEmployeeInfo info = mbOrgNonEmployeeMapper.selectByPrimaryKey(mbFreshPassengerRelation.getFreshUid());
            MbOrgNonEmployeeInfo oldValue = new MbOrgNonEmployeeInfo();
            if (info != null) {
                BeanUtils.copyProperties(info, oldValue);
            }
            info.setName(ffpModifyRequest.getFullName());
            if(StringUtils.isNotBlank(ffpModifyRequest.getFirstName()) && StringUtils.isNotBlank(ffpModifyRequest.getLastName())){
                info.setFirstEnName(ffpModifyRequest.getFirstName());
                info.setLastEnName(ffpModifyRequest.getLastName());
            } else if(StringUtils.isNotBlank(ffpModifyRequest.getSurname()) && StringUtils.isNotBlank(ffpModifyRequest.getGivenname())){
                info.setFirstEnName(ffpModifyRequest.getGivenname());
                info.setLastEnName(ffpModifyRequest.getSurname());
            }else{
                log.error("firstName,lastName error:{},{},{},{}",
                        ffpModifyRequest.getFirstName() ,ffpModifyRequest.getLastName(),ffpModifyRequest.getSurname() ,ffpModifyRequest.getGivenname());
            }
            info.setBirthday(Date.from(ZonedDateTime.of(LocalDate.parse(ffpModifyRequest.getBirthday(), DateTimeFormatter.ofPattern(DateUtil.DF_YMD)), LocalTime.MIN, ZoneId.of("GMT+8")).toInstant()));
            info.setEmail(ffpModifyRequest.getEmail());
            if (ffpModifyRequest.getSex() != null) {
                String gender = ffpModifyRequest.getSex().equals(0) ? "M" : "F";
                info.setGender(gender);
            }
            NameInfoBo nameInfoBo = JsonUtils.parse(JsonUtils.toJsonString(ffpModifyRequest),NameInfoBo.class);
            if(StrUtils.checkNameInfo(nameInfoBo)){
                info.setNameInfo(JsonUtils.toJsonString(nameInfoBo));
            }
            info.setNationality(ffpModifyRequest.getNationality());
            String device = ffpModifyRequest.getDevice();
            info.setMobilePhone(ffpModifyRequest.getCountryCode() + " " + ffpModifyRequest.getPhoneNum());

            //更新员工表
            try {
                mbOrgNonEmployeeMapper.updateByPrimaryKeySelective(info);
//                updateOperateLog(oldValue, info);
            } catch (Exception e) {
                log.error("更新操作获取oldValue失败，OrganizationEmployeeServiceImpl.modifyFfpItem");
            }

            //更新freshpassenger
            MbFreshPassenger mbFreshPassenger = new MbFreshPassenger();
            mbFreshPassenger.setNonEmployeeUid(Long.valueOf(mbFreshPassengerRelation.getFreshUid()));
            mbFreshPassenger.setName(ffpModifyRequest.getFullName());
            mbFreshPassenger.setEnName(ffpModifyRequest.getFirstName() + "/" + ffpModifyRequest.getLastName());
            freshPassengerService.updateByNonEmployeeId(mbFreshPassenger);

            List<CardInfo> cardIdList = ffpModifyRequest.getCardIdList();
            List<MbOrgUserIdcard> existCardList = organizationUserIdCardService.findByNonEmployeeId(info.getId());
            List<MbOrgUserIdcard> needDeleteCardList = existCardList.stream().filter(e -> checkDeleteCard(e, cardIdList)).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(needDeleteCardList)){
                organizationUserIdCardService.deleteByList(needDeleteCardList);
            }
            if (CollectionUtils.isNotEmpty(cardIdList)) {
                // for (CardInfo cardInfo : cardIdList) {
                // List<MbOrgUserIdcard> mbOrgUserIdCardList =
                // organizationUserIdCardService.findByTypeAndNo(cardInfo.getCardType(), cardInfo.getCardId());
                // log.info("mbOrgUserIdCardList:{}", JsonUtils.toJSONString(mbOrgUserIdCardList));
                // if (CollectionUtils.isNotEmpty(mbOrgUserIdCardList)){
                // for (MbOrgUserIdcard userIdCard:mbOrgUserIdCardList){
                // String nonEmployeeIdStr =
                // Optional.ofNullable(userIdCard.getNonEmployeeId()).map(String::valueOf).orElse("");
                // if (!mbFreshPassengerRelation.getFreshUid().equals(nonEmployeeIdStr)){
                // throw new CorpBusinessException(OrganizationResponseCodeEnum.CARD_TYPE_EXISTS,
                // Optional.ofNullable(CardTypeEnum.getByCode(cardInfo.getCardType())).map(CardTypeEnum::getDesc).orElse(CardTypeEnum.UNKNOWN.getDesc()),
                // cardInfo.getCardId());
                // }
                // }
                // }
                // }

                //organizationUserIdCardService.deleteByNonEmployeeUid(Long.valueOf(mbFreshPassengerRelation.getFreshUid()));
                for (CardInfo cardInfo : cardIdList) {
                    MbOrgUserIdcard param = new MbOrgUserIdcard();
                    param.setCardNo(cardInfo.getCardId());
                    param.setCardType(cardInfo.getCardType());
                    param.setNonEmployeeId(info.getId());
                    if (StringUtils.isNotBlank(cardInfo.getValidDate())){
                        param.setTimeLimit(DateUtil.stringToDate(cardInfo.getValidDate(), DateUtil.DF_YMD));
                    }
                    // 判断用户是否存在该类型证件
                    MbOrgUserIdcard byEmployeeUidAndType = organizationUserIdCardService.findByNonEmployeeUidAndType(info.getId(), param.getCardType());
                    if (byEmployeeUidAndType == null) {
                        // 不存在，则插入
                        organizationUserIdCardService.save(param);
                    } else {
                        // 存在，则更新
                        organizationUserIdCardService.updateNonEmployeeCard(param);
                    }
                }
            }

            //逻辑删除常旅客卡
            List<FrequentCardListBean> frequentCardsList = ffpModifyRequest.getFrequentCardsList();
            if (frequentCardsList != null) {
                List<MbOrgUserFfpinfo> userFfpinfos = organizationUserFfpService.listByNonEmployeeIds(Collections.singletonList(mbFreshPassenger.getNonEmployeeUid()));
                userFfpinfos.forEach(i -> {
                    i.setIsDeleted(true);
                    organizationUserFfpService.update(i);
                });


                Map<String, Integer> map = Maps.newHashMap();
                for (int i = 0; i < frequentCardsList.size(); i++) {
                    if (!RegularUtils.isNumer(frequentCardsList.get(i).getCardNo())) {
                        throw new CorpBusinessException(OrganizationResponseCodeEnum.FREQUENT_CARD_NON_NUMBER, frequentCardsList.get(i).getCardNo());
                    }
                    if (map.containsKey(frequentCardsList.get(i).getCardNo())) {
                        map.put(frequentCardsList.get(i).getCardNo(), map.get(frequentCardsList.get(i).getCardNo()) + 1);
                    } else {
                        map.put(frequentCardsList.get(i).getCardNo(), 1);
                    }
                }

                if (MapUtils.isNotEmpty(map)) {
                    for (Entry<String, Integer> entry : map.entrySet()) {
                        int value = entry.getValue();
                        if (value > 1) {
                            throw new CorpBusinessException(OrganizationResponseCodeEnum.FREQUENT_CARD_EXISTS, value);
                        }
                    }
                }

                //更新常旅客卡
                frequentCardsList.forEach(i -> {
                    MbOrgUserFfpinfo param = new MbOrgUserFfpinfo();
                    param.setNonEmployeeUid(info.getId());
                    param.setAirline(i.getCardId());
                    param.setFfpno(i.getCardNo());
                    organizationUserFfpService.save(param);
                });

            }
        }
        //更新缓存
        baseUserInfo.setAccountName(ffpModifyRequest.getFullName());
        return JSONResult.success(new UpdateFfpResultVo(ffpModifyRequest.getFullName()));
    }

    private Boolean checkDeleteCard(MbOrgUserIdcard mbOrgUserIdcard, List<CardInfo> cardIdList) {
        return CollectionUtils.isEmpty(cardIdList.stream().filter(e -> mbOrgUserIdcard.getCardType().equals(e.getCardType())).collect(Collectors.toList()));
    }

    private void updateUserLogin(MbUserLoginVo userLogin) {
        MbUserLogin oldUserLoginInfo = userLoginService.getByUid(userLogin.getUid());
        // 用户名、手机号、区号有修改就更新用户登录信息
        if (!Objects.equals(oldUserLoginInfo.getUserName(), userLogin.getUserName()) ||
                !Objects.equals(oldUserLoginInfo.getCountryCode(), userLogin.getCountryCode())) {
            //修改用户手机号码时不修改登录账号
            userLogin.setPhoneNum(oldUserLoginInfo.getPhoneNum());
            userLoginService.updateNameAndPhone(userLogin, false);
        }
    }

    private void findAllDirectChildDepartment(String statOrgId, Map<String, List<MbOrgInfo>> parentIdMapList, List<String> returnList) {
        List<MbOrgInfo> children = parentIdMapList.get(statOrgId);
        if (CollectionUtils.isNotEmpty(children)) {
            for (MbOrgInfo child : children) {
                if (child.getOrgType().equals(OrganizationConst.DEPARTMENT)) {
                    returnList.add(child.getOrgId());
                    findAllDirectChildDepartment(child.getOrgId(), parentIdMapList, returnList);
                } else {
                    continue;
                }
            }
        }
    }

    /**
     * 根据关键字搜索公司
     *
     * @param request 搜索请求
     * @return 搜索结果
     */
    @Override
    public ResisterOrgResponseVO search(RegisterOrgRequest request) {
        String keyword = Optional.ofNullable(request).map(RegisterOrgRequest::getKeyword).orElse(null);
        List<MbOrgInfo> mbOrgInfos = this.fuzzyByNameAndType(keyword, OrgTypeEnum.C.getCode(), "T");

        /**
         * 	数据权限
         * 		部门对账员:  数据权限默认只包含部门 (不处理公司数据)
         * 		企业对账员: 	数据权限默认只包含公司 (不处理部门数据)
         */
        BaseUserInfo baseUserInfo = UserInfoContext.getContextParams(BaseUserInfo.class);
        if (baseUserInfo.getDataPermissionControl() && Objects.nonNull(baseUserInfo.getRoleId()) && !Boolean.TRUE.equals(baseUserInfo.getBgUser())) {
            ResourceInfo resourceInfo = manager.getResource(baseUserInfo.getRoleId().toString(), ResourceInfo.class);
            //数据权限只有部门则 只展示部门数据      如数据权限包含公司  则只展示公司数据
            List<ResourceInfo.DeptInfo> resourceData = Optional.ofNullable(resourceInfo.getDeptInfos()).orElse(new ArrayList<>());
            Set<String> orgIds = resourceData.stream().map(ResourceInfo.DeptInfo::getOrgId).collect(Collectors.toSet());
            mbOrgInfos = mbOrgInfos.stream().filter(item -> orgIds.contains(item.getOrgId())).collect(Collectors.toList());
        }

        List<CorpNode> collect = mbOrgInfos.stream()
                .map(mbOrgInfo -> new CorpNode().setCorpId(mbOrgInfo.getOrgId()).setCorpName(mbOrgInfo.getName()))
                .collect(Collectors.toList());
        return ResisterOrgResponseVO.create(collect);
    }

    private List<MbOrgInfo> fuzzyByNameAndType(String keyword, String code, String valid) {
        List<MbOrgInfo> mbOrgInfos = mbOrgInfoMapper.fuzzyByNameAndType(null, code, valid);
        if (StringUtils.isNotBlank(keyword)){
            mbOrgInfos = mbOrgInfos.stream().filter(e->e.getName().contains(keyword)).collect(Collectors.toList());
        }
        return mbOrgInfos;
    }

    /**
     * 根据公司id搜索部门不包含子公司
     *
     * @param request 搜索公司部门请求
     * @return 公司下部门
     */
    @Override
    public JSONResult corpSearch(RegisterOrgRequest request) {
        RegisterCorpResponse registerCorpResponse = new RegisterCorpResponse();
        String corpId = request.getCorpId();
        // 获取所有有效的组织(包含公司和部门)
        MbOrgInfo selectParam = new MbOrgInfo();
        selectParam.setIsBackground(false);
        selectParam.setDeleteTime(new Date(0));
        selectParam.setValid("T");
        List<MbOrgInfo> mbOrgInfos = mbOrgInfoMapper.select(selectParam);
        // 获取所有有效的部门
        List<MbOrgInfo> allValidDept =
                mbOrgInfos.stream().filter(mbOrgInfo -> StringUtils.equals(mbOrgInfo.getOrgType(), OrgTypeEnum.D.getCode(), false))
                        .collect(Collectors.toList());
        registerCorpResponse.setDeptObj(getValidOrg(allValidDept, corpId));
        // 获取所有有效的公司
        List<MbOrgInfo> allValidCorps =
                mbOrgInfos.stream().filter(mbOrgInfo -> StringUtils.equals(mbOrgInfo.getOrgType(), OrgTypeEnum.C.getCode(), false))
                        .collect(Collectors.toList());
        registerCorpResponse.setSuperiorCorp(getCurrentAndParentCorpName(allValidCorps, corpId));
        return JSONResult.success(registerCorpResponse);

    }

    /**
     * 获取公司下的所有有效的部门
     *
     * @param allValidDept 所有有效的部门
     * @param corpId       公司id
     * @return 所有有效的部门
     */
    private List<CorpNode> getValidOrg(@NonNull List<MbOrgInfo> allValidDept, @NonNull String corpId) {
        if (CollectionUtils.isNotEmpty(allValidDept)) {
            Map<String, CorpNode> departmentMap = new HashMap<>(allValidDept.size());
            for (MbOrgInfo mbOrgInfo : allValidDept) {
                String orgId = mbOrgInfo.getOrgId();
                CorpNode corpNode = departmentMap
                        .computeIfAbsent(orgId, s -> new CorpNode().setChildren(new ArrayList<>()).setDeptId(s));
                corpNode.setDeptName(mbOrgInfo.getName()).setDeptId(orgId);
                String parentId = mbOrgInfo.getParentId();
                CorpNode parentCorp = departmentMap
                        .computeIfAbsent(parentId, s -> new CorpNode().setChildren(new ArrayList<>()).setDeptId(s));
                parentCorp.getChildren().add(corpNode);
            }
            return Optional.ofNullable(departmentMap.get(corpId)).map(CorpNode::getChildren)
                    .orElse(Collections.emptyList());
        }
        return Collections.emptyList();
    }

    /**
     * 根据公司id查询父公司和当前公司的名字
     *
     * @param allValidCorp 所有有效的公司集合
     * @param corpId       公司id
     * @return 父公司和当前公司的名字
     */
    private String getCurrentAndParentCorpName(@NonNull List<MbOrgInfo> allValidCorp, @NonNull String corpId) {
        String currentCorpName;
        String parentCorpName;
        if (CollectionUtils.isEmpty(allValidCorp)) {
            return null;
        }
        // 当前公司的信息
        MbOrgInfo orgInfo = allValidCorp.stream().filter(mbOrgInfo -> corpId.equals(mbOrgInfo.getOrgId())).findFirst()
                .orElseThrow(() -> new CommonException(112121, "不存在"));
        currentCorpName = orgInfo.getName();
        // 父公司id
        String parentId = orgInfo.getParentId();
        if (StringUtils.isBlank(parentId)) {
            return currentCorpName;
        }
        parentCorpName = allValidCorp.stream().filter(mbOrgInfo -> parentId.equals(mbOrgInfo.getOrgId())).findFirst()
                .map(MbOrgInfo::getName).orElse(null);
        return StringUtils.isNotBlank(parentCorpName) ? String.join(">", parentCorpName, currentCorpName) :
                currentCorpName;

    }

    /**
     * 查询组织下的所有部门信息不穿透
     *
     * @param orgId
     * @return
     */
    @Override
    public Set<String> getAllChildDepartmentListNoPenetrate(String orgId) {
        //查询所有组织信息
        List<MbOrgInfo> mbOrgInfoList = this.listAll();
        Map<String, List<MbOrgInfo>> parentIdMap = mbOrgInfoList.stream()
                .filter(p -> p.getParentId() != null).filter(x -> OrgTypeEnum.D.getCode().equals(x.getOrgType()))
                .collect(Collectors.groupingBy(MbOrgInfo::getParentId));
        Set<String> allDepartmentSet = new HashSet<>();
        //查询所有部门信息
        getAllChildDepartmentListNoPenetrate(parentIdMap, Collections.singletonList(orgId), allDepartmentSet);
        return allDepartmentSet;
    }

    @Override
    public List<String> listAllValidOrgId() {
        return mbOrgInfoMapper.selectAllValidOrgId();
    }

    @Override
    public SearchInvoiceInfoResponseBO searchInvoiceInfo(SearchInvoiceInfoRequestBO request) {
        if (BooleanUtils.isTrue(request.getQueryAll())) {
            List<MbCommonInvoiceInfo> invoiceInfoList = commonInvoiceInfoService
                .listAllOrgIdReal(request.getQueryKey());
            return SearchInvoiceInfoResponseBO.create(buildInvoiceInfoList(invoiceInfoList));
        }

        String corpId = request.getCorpId();
        if (StringUtils.isBlank(corpId)) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.CORP_ID_NULL);
        }
        List<MbCommonInvoiceInfo> invoiceInfoList = commonInvoiceInfoService.listByOrgIdReal(corpId);
        if (CollectionUtils.isEmpty(invoiceInfoList)) {
            return SearchInvoiceInfoResponseBO.empty();
        }
        List<InvoiceInfoBO> result = buildInvoiceInfoList(invoiceInfoList);
        return SearchInvoiceInfoResponseBO.create(result);
    }

    private List<InvoiceInfoBO> buildInvoiceInfoList(List<MbCommonInvoiceInfo> invoiceInfoList) {
        return invoiceInfoList.stream().map(e -> {
            InvoiceInfoBO bo = new InvoiceInfoBO();
            bo.setAccountBank(e.getAccountBank());
            bo.setAccountCardNo(e.getAccountCardNo());
            bo.setCorporationAddress(e.getCorporationAddress());
            bo.setCorporationPhone(e.getCorporationPhone());
            bo.setInvoiceTitle(e.getInvoiceTitle());
            bo.setTaxId(e.getTaxId());
            return bo;
        }).collect(Collectors.toList());
    }

    @Override
    public OrgInfoVo searchOrgInfo(SearchOrgInfoRequestBO requestBO) {
        // 查找组织结构信息
        MbOrgInfo mbOrgInfo = this.findByOrgId(requestBO.getOrgId());
        if (mbOrgInfo == null) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.ORG_INFO_IS_NULL);
        }
        OrgInfoVo orgInfoVo = new OrgInfoVo();
        BeanUtils.copyProperties(mbOrgInfo, orgInfoVo);
        return orgInfoVo;
    }

    @Override
    public List<GetFfBasicsInfoResponse> getFfBasicsInfo(String uid) {
        List<MbFreshPassengerRelationDTO> freshPassengerRelationList = mbFreshPassengerRelationMapper.pageByUid(uid);
        List<GetFfBasicsInfoResponse> response = ListUtils.copyList(freshPassengerRelationList, GetFfBasicsInfoResponse.class);
        return response;
    }


    private Set<String> getAllChildDepartmentListNoPenetrate(Map<String, List<MbOrgInfo>> orgMap, List<String> orgIds, Set<String> allDepartmentSet) {
        List<String> childDepartmentList = orgIds.stream().map(orgMap::get).filter(Objects::nonNull).reduce(BaseUtils::combine).orElse(new ArrayList<>()).stream().map(MbOrgInfo::getOrgId).collect(Collectors.toList());
        if (!org.apache.commons.collections4.CollectionUtils.isEmpty(childDepartmentList)) {
            allDepartmentSet.addAll(childDepartmentList);
            getAllChildDepartmentListNoPenetrate(orgMap, childDepartmentList, allDepartmentSet);
        }
        return allDepartmentSet;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean batchTransferEmployeeOrgInfo(TransferEmployeeOrgInfoVo request) {
        log.info("开始批量修改组织信息,request:{}", JsonUtils.toJsonString(request));
        // 检测输入不能为空
        checkRequestParams(request);

        if("organizationChange".equalsIgnoreCase(request.getQueryType())){
            this.organizationChange(request);
        }

        //修改组织关联表
        userOrgRelationService.batchUpdateUserOrgRelation(request);
        //修改用户新鲜度表
        freshPassengerService.batchUpdateFreshPassenger(request);

        request.getEmployeeOrgInfoList().forEach(i -> {
            // 新老部门不同时才清老数据
            if(!Objects.equals(request.getNewOrgId(), i.getOldOrgId())) {
                log.info("开始清老数据,uid:{}",i.getUid());
                //删除代订信息
                bookingRelationService.deleteBookingRelationByUid(i.getUid());
                //删除审批配置
                approvalClientLoader.deleteFlowTmpl(i.getUid());
                //删除角色
                userRoleLoader.deleteRoleByUid(i.getUid());
                // 删除岗位信息
                jobService.removeJobIdByUid(i.getUid());
                log.info("删除岗位信息成功,uid:{}",i.getUid());
                // 更改出差申请单状态为已失效，失效申请单加系统操作记录
                applyTripClientLoader.updateApplyTripStatusExpired(i.getUid());
            }
        });
        // 保存修改历史
        organizationChangeHistoryLoader.batchSave(buildHistoryModel(request));
        return true;
    }

    /**
     * 检验部门是否发生变更,如果没有变更抛出异常中断流程
     * @param request
     */
    private static void organizationChange(TransferEmployeeOrgInfoVo request) {
        // 检测机构有没有发生变化
        String newOrgId = request.getNewOrgId();
        List<String> oldOrgIdList = request.getEmployeeOrgInfoList().stream()
                .map(TransferEmployeeOrgInfoVo.EmployeeOrgInfo::getOldOrgId)
                .distinct().collect(Collectors.toList());
        if(CollectionUtil.isNotEmpty(oldOrgIdList) && oldOrgIdList.size() > 1){
            throw new CorpBusinessException(OrganizationResponseCodeEnum.OLD_ORGID_ERROR);
        }
        if(newOrgId.equalsIgnoreCase(oldOrgIdList.get(0))){
            throw new CorpBusinessException(OrganizationResponseCodeEnum.OLD_ORGID_NOT_CHANGE);
        }
    }

    private List<OrganizationChangeHistoryModel> buildHistoryModel(TransferEmployeeOrgInfoVo request){
        if (request == null){
            return Collections.emptyList();
        }
        if (CollectionUtils.isEmpty(request.getEmployeeOrgInfoList())){
            return Collections.emptyList();
        }
        List<String> uids = request.getEmployeeOrgInfoList().stream().map(TransferEmployeeOrgInfoVo.EmployeeOrgInfo::getUid).collect(Collectors.toList());
        List<MbOrgEmployeeInfo> mbOrgEmployeeInfoList = organizationEmployeeService.listByUids(uids);
        if (CollectionUtils.isEmpty(mbOrgEmployeeInfoList)){
            return Collections.emptyList();
        }
        Map<String, MbOrgEmployeeInfo> map = mbOrgEmployeeInfoList.stream().collect(Collectors.toMap(MbOrgEmployeeInfo::getUid,Function.identity(), (t1, t2) -> t1));
        return request.getEmployeeOrgInfoList().stream().map(t->{
            OrganizationChangeHistoryModel model = new OrganizationChangeHistoryModel();
            MbOrgEmployeeInfo mbOrgEmployeeInfo = map.get(t.getUid());
            if (mbOrgEmployeeInfo == null){
                throw new CorpBusinessException(OrganizationResponseCodeEnum.QUERY_USER_ORG_INFO_ERROR);
            }
            model.setEmployeeId(mbOrgEmployeeInfo.getId());
            model.setCurrentOrgId(request.getNewOrgId());
            model.setBeforeOrgId(t.getOldOrgId());
            model.setOperateType(EmployeeOperateEnum.TRANSFER.name());
            return model;
        }).collect(Collectors.toList());
    }

    private  void checkRequestParams(TransferEmployeeOrgInfoVo request) {
        if (StringUtils.isBlank(request.getNewOrgId())){
            throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "newOrgId");
        }
        if (CollectionUtils.isEmpty(request.getEmployeeOrgInfoList())){
            throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "employeeOrgInfoList");
        }
        request.getEmployeeOrgInfoList().forEach(item ->{
            if (StringUtils.isBlank(item.getUid())){
                throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "uid");
            }
            if (StringUtils.isBlank(item.getOldOrgId())){
                throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "oldOrgId");
            }
        });
    }

    /**
     * 默认部门查出父级公司下所有公司部门（不包括自己默认部门）
     * 普通部门
     * @param request
     * @return
     */
    @Override
    public GetOrgTreeRsp getOrgTree(GetOrgTreeRequest request) {
        StringBuilder logContext = new StringBuilder();
        LogSplicingUtils.addLogContext(logContext, "request : %s", JsonUtils.toJsonString(request));
        try{
            long startTime = System.currentTimeMillis();
            //查询所有组织
            List<MbOrgInfo> orgInfoAll = mbOrgInfoMapper.listAll();
            //筛选默认部门
            if (!request.getIsShowDefaultOrg()){
                orgInfoAll = orgInfoAll.stream().filter(item -> item.getId() > 0).collect(Collectors.toList());
            }

            //按组织ID进行Map
            Map<String, MbOrgInfo> orgIdMap = new HashMap<>(orgInfoAll.size());
            for (MbOrgInfo orgInfo : orgInfoAll) {
                orgIdMap.put(orgInfo.getOrgId(), orgInfo);
            }

            Map<String, List<MbOrgInfo>> parentIdMap= orgInfoAll.stream().filter(e -> StringUtils.isNotBlank(e.getParentId())).collect(Collectors.groupingBy(MbOrgInfo::getParentId));

            //查询员工
            Map<String, List<SearchCorpEmpResponse>> empMap = new HashMap<>();
            if (request.getIsSelectUser()){
                List<SearchCorpEmpResponse> empResponseList = organizationEmployeeService.selectEmployeeByOrgIds(orgInfoAll.stream().map(MbOrgInfo::getOrgId).collect(Collectors.toList()));
                empMap = empResponseList.stream().collect(Collectors.groupingBy(SearchCorpEmpResponse::getOrgId));
            }
            LogSplicingUtils.addLogContext(logContext, "数据组装耗时：%s", (System.currentTimeMillis() - startTime));

            startTime = System.currentTimeMillis();
            MbOrgInfo mbOrgInfo = orgIdMap.get(request.getOrgId());
            GetOrgTreeRsp getorgTreeRsp = getGetOrgTreeRsp(request, mbOrgInfo, orgIdMap, empMap, parentIdMap, logContext, startTime);
            return getorgTreeRsp;
        }catch (Exception e){
            e.printStackTrace();
            log.info("发生异常：{}", e);
        }finally {
            log.info("组织树：{} {}", System.lineSeparator(), logContext.toString());
        }
        return null;
    }

    @Override
    public List<GetOrgTreeRsp> getOrgTreeWhole() {
        List<GetOrgTreeRsp> getOrgTreeRspList = new ArrayList<>();
        //查询所有组织
        List<MbOrgInfo> orgInfoAll = mbOrgInfoMapper.listAll();
        // 顶级集团数据
        List<MbOrgInfo> topLevelList = orgInfoAll.stream().filter(m -> m.getLevel() == 1).collect(Collectors.toList());
        if(CollectionUtil.isEmpty(topLevelList)){
            return getOrgTreeRspList;
        }
        for (MbOrgInfo mbOrgInfo : topLevelList) {
            getOrgTreeRspList.add(organizationInfoService.getOrgTree(new GetOrgTreeRequest(mbOrgInfo.getOrgId(), false)));
        }
        return getOrgTreeRspList;
    }

    private GetOrgTreeRsp getGetOrgTreeRsp(GetOrgTreeRequest request, MbOrgInfo mbOrgInfo, Map<String, MbOrgInfo> orgIdMap, Map<String, List<SearchCorpEmpResponse>> empMap,
                                           Map<String, List<MbOrgInfo>> parentIdMap, StringBuilder logContext, long startTime) {
        GetOrgTreeRsp parentTree = new GetOrgTreeRsp();
        //默认部门ID < 0
        //组织父级基本信息
        if (mbOrgInfo.getId() > 0){
            String orgId = mbOrgInfo.getOrgId();
            if (StringUtils.equals(mbOrgInfo.getOrgType(), OrgTypeEnum.D.getCode(), false)){
                orgId = getTreeParentId(orgIdMap, mbOrgInfo.getOrgId());
            }
            MbOrgInfo parentOrgInfo = orgIdMap.get(orgId);
            if(ObjectUtil.isNull(parentOrgInfo)){
                return null;
            }
            parentTree.setId(parentOrgInfo.getOrgId());
            parentTree.setOrgId(parentOrgInfo.getOrgId());
            parentTree.setLabel(parentOrgInfo.getName());
            parentTree.setType(parentOrgInfo.getOrgType());
            parentTree.setValid(parentOrgInfo.getValid());
            parentTree.setOid(parentOrgInfo.getId());
            parentTree.setLevel(parentOrgInfo.getLevel());
            if (request.getIsSelectUser()){
                parentTree.setEmpList(getTreeEmpList(empMap, parentOrgInfo.getOrgId()));
            }
            parentTree.setChildren(getOrgTreeRecursion(parentIdMap, parentOrgInfo.getOrgId(), request.getIsErgodic(), logContext, request.getIsSelectUser(), empMap));
        } else{
            MbOrgInfo parentOrgInfo = orgIdMap.get(mbOrgInfo.getParentId());
            if(ObjectUtil.isNull(parentOrgInfo)){
                return null;
            }
            parentTree.setId(parentOrgInfo.getOrgId());
            parentTree.setOrgId(parentOrgInfo.getOrgId());
            parentTree.setLabel(parentOrgInfo.getName());
            parentTree.setType(parentOrgInfo.getOrgType());
            parentTree.setValid(parentOrgInfo.getValid());
            parentTree.setOid(parentOrgInfo.getId());
            parentTree.setLevel(parentOrgInfo.getLevel());
            if (request.getIsSelectUser()){
                parentTree.setEmpList(getTreeEmpList(empMap, parentOrgInfo.getOrgId()));
            }
            parentTree.setChildren(getOrgTreeRecursion(parentIdMap, parentOrgInfo.getOrgId(), request.getIsErgodic(), logContext, request.getIsSelectUser(), empMap));
        }
        LogSplicingUtils.addLogContext(logContext, "数据组装耗时：%s", (System.currentTimeMillis() - startTime));
        return parentTree;
    }

    @Override
    public String createOrgCode(String orgId) {
        MbOrgInfo orgInfo = null;
        if (ObjectUtils.isEmpty(orgId)) {
            Long orgCount = mbOrgInfoMapper.selectOrgCount();
            do {
                ++orgCount;
                orgInfo = organizationInfoService.findByOrgId(String.valueOf(orgCount));
            }
            while (orgInfo != null);
            return orgCount.toString();
        }
        else {
            StringBuffer sb = new StringBuffer();
            String newOrgCode = new String();
            MbOrgInfo parentOrgInfo = findByOrgId(orgId);
            List<MbOrgInfo> mbOrgInfos = mbOrgInfoMapper.selectOrgByParentId(parentOrgInfo.getOrgId());
            int length = mbOrgInfos.size();
            sb.append(parentOrgInfo.getOrgId()).append("-");
            do {
                newOrgCode = sb.toString() + ++length;
                orgInfo = organizationInfoService.findByOrgId(newOrgCode);
            }
            while (orgInfo != null);
            return newOrgCode;
        }
    }

    @Override
    public MbOrgInfo findByBusinessCode(String businessCode) {
        MbOrgInfo mbOrgInfo = new MbOrgInfo();
        mbOrgInfo.setBusinessCode(businessCode);
//        mbOrgInfo.setIsDeleted(false);
        mbOrgInfo.setDeleteTime(new Date(0));
        return mbOrgInfoMapper.selectOne(mbOrgInfo);
    }

    @Override
    public List<MbOrgInfo> listByBusinessCode(List<String> businessCode) {
        if (CollectionUtils.isEmpty(businessCode)) {
            return new ArrayList<>();
        }
        return mbOrgInfoMapper.listByBusinessCodeWithoutBackground(businessCode);
    }

    @Override
    public MbOrgInfo selectOneByOrgId(String orgId) {
        if (orgId == null) {
            return new MbOrgInfo();
        }
        return mbOrgInfoMapper.selectOneByOrgId(orgId);
    }

    /**
     * 组织人员信息
     * @param empMap
     * @param orgId
     * @return
     */
    public List<GetOrgTreeRsp.GetOrgTreeEmp> getTreeEmpList(Map<String, List<SearchCorpEmpResponse>> empMap, String orgId){
        List<SearchCorpEmpResponse> empList = empMap.get(orgId);
        if (CollectionUtils.isEmpty(empList)){
            return new ArrayList<>();
        }
        List<GetOrgTreeRsp.GetOrgTreeEmp> treeEmpList = new ArrayList<>();
        for (SearchCorpEmpResponse emp:empList){
            GetOrgTreeRsp.GetOrgTreeEmp treeEmp = new GetOrgTreeRsp.GetOrgTreeEmp();
            treeEmp.setUid(emp.getUid());
            treeEmp.setUserName(emp.getName());
            treeEmpList.add(treeEmp);
        }
        return treeEmpList;
    }

    /**
     * 获取上一级公司ID
     * @param orgIdMap
     * @param orgId
     * @return
     */
    public String getTreeParentId(Map<String, MbOrgInfo> orgIdMap, String orgId){
        MbOrgInfo mbOrgInfo = orgIdMap.get(orgId);
        if(ObjectUtil.isNull(mbOrgInfo)){
            return "";
        }
        if (StringUtils.equals(mbOrgInfo.getOrgType(), OrgTypeEnum.C.getCode(), false)){
            return mbOrgInfo.getOrgId();
        }
        return getTreeParentId(orgIdMap, mbOrgInfo.getParentId());
    }

    /**
     * @param parentIdMap 父级组织对应信息
     * @param orgId 组织ID
     * @param isErgodic 是否穿透子公司 true：穿透 false：不穿透
     * @return
     */
    public List<GetOrgTreeRsp> getOrgTreeRecursion(Map<String, List<MbOrgInfo>> parentIdMap,
                                                        String orgId, Boolean isErgodic, StringBuilder logContext, Boolean isSelectUser, Map<String, List<SearchCorpEmpResponse>> empMap){
        List<GetOrgTreeRsp> children = new ArrayList<>();
        //判断是否有子级
        List<MbOrgInfo> mbOrgInfos = parentIdMap.get(orgId);
        if (CollectionUtils.isEmpty(mbOrgInfos)){
            return children;
        }
        //遍历子节点
        for(MbOrgInfo orgInfo:mbOrgInfos){
            //如果子节点是公司就不遍历了->不穿透子公司
            if (BooleanUtils.isFalse(isErgodic) && StringUtils.equals(orgInfo.getOrgType(), OrgTypeEnum.C.getCode(), false)){
                continue;
            }
            //默认部门不展示
            if (orgInfo.getId() < 0){
                continue;
            }
            GetOrgTreeRsp childrenTree = new GetOrgTreeRsp();
            childrenTree.setId(orgInfo.getOrgId());
            childrenTree.setOrgId(orgInfo.getOrgId());
            childrenTree.setLabel(orgInfo.getName());
            childrenTree.setType(orgInfo.getOrgType());
            childrenTree.setValid(orgInfo.getValid());
            childrenTree.setOid(orgInfo.getId());
            childrenTree.setLevel(orgInfo.getLevel());
            if (isSelectUser){
                childrenTree.setEmpList(getTreeEmpList(empMap, orgInfo.getOrgId()));
            }
            childrenTree.setChildren(getOrgTreeRecursion(parentIdMap, orgInfo.getOrgId(), isErgodic, logContext, isSelectUser, empMap));
            children.add(childrenTree);
        }
        return children;
    }

    @Override
    public JSONResult<Boolean> modifyPassenger(PassengerModifyRequest request, BaseUserInfo baseUserInfo) {
        //ObjectStringTrimUtils.allFieldRemoveWarp(request);

        Integer employeeType = request.getEmployeeType();
        if (employeeType == null){
            throw new CorpBusinessException(OrganizationResponseCodeEnum.EMPLOYEE_TYPE_IS_NULL);
        }
        if (Objects.isNull(request.getUid()) && Objects.isNull(request.getNoEmployeeId())){
            throw new CorpBusinessException(OrganizationResponseCodeEnum.UID_IS_NULL);
        }
        if (Objects.isNull(request.getRelationFlag())){
            request.setRelationFlag(true);
        }
        // 兼容fullName与name，优先使用fullName
        if (StringUtils.isBlank(request.getFullName())){
            request.setFullName(request.getName());
        }
        log.info("当前修改乘机人信息的request为:{}", JsonUtils.toJsonString(request));

        // 部分证件号码转大写
        if (Objects.nonNull(request.getCardType()) && StringUtils.isNotBlank(request.getCardId()) && CardEnum.needUpperCaseCard(request.getCardType().toString())){
            request.setCardId(request.getCardId().toUpperCase());
        }

        boolean needWarn = false;
        //处理员工
        if (employeeType == 0 || employeeType == 1){
            //更新员工信息表
            MbOrgEmployeeInfo info = organizationEmployeeService.findByUid(request.getUid());
            if (Objects.nonNull(request.getFirstName()) && Objects.nonNull(request.getLastName())) {
                if (request.getFirstName().equals(info.getLastEnName()) || request.getLastName().equals(info.getFirstEnName())) {
                    needWarn = true;
                }
            }
            info.setName(request.getFullName());
            if(StringUtils.isNotBlank(request.getFirstName()) && StringUtils.isNotBlank(request.getLastName())){
                info.setFirstEnName(request.getFirstName());
                info.setLastEnName(request.getLastName());
            }
            info.setNationality(request.getNationality());
            info.setEmail(request.getMail());
            if (DateUtil.isDateDay(request.getBirthday())){
                info.setBirthday(Date.from(ZonedDateTime.of(LocalDate.parse(request.getBirthday(), DateTimeFormatter.ofPattern(DateUtil.DF_YMD)), LocalTime.MIN, ZoneId.of("GMT+8")).toInstant()));
            }
            if (request.getSex() != null){
                info.setGender(request.getSex().equals(0) ? "M" : "F");
            }
            info.setMobilePhone(request.getPhoneNum());
            info.setAreaCode(request.getCountryCode());
            NameInfoBo nameInfoBo = JsonUtils.parse(JsonUtils.toJsonString(request),NameInfoBo.class);
            if(StrUtils.checkNameInfo(nameInfoBo)){
                info.setNameInfo(JsonUtils.toJsonString(nameInfoBo));
            }
            organizationEmployeeService.updateEmployeeSelective(info);

            //更新出行人新鲜度表
            MbFreshPassenger mbFreshPassenger = new MbFreshPassenger();
            mbFreshPassenger.setEmployeeUid(request.getUid());
            mbFreshPassenger.setName(request.getFullName());
            mbFreshPassenger.setEnName(request.getSurname() + "/" + request.getGivenname());
            freshPassengerService.updateByEmployeeId(mbFreshPassenger);

            //更新证件信息表
            if (Objects.nonNull(request.getCardType())) {
                MbOrgUserIdcard employeeCard = organizationUserIdCardService.findByEmployeeUidAndType(request.getUid(), request.getCardType());
                boolean update = true;
                if (Objects.isNull(employeeCard)) {
                    employeeCard = new MbOrgUserIdcard();
                    update = false;
                }
                convertCardInfo(employeeCard, request);
                employeeCard.setEmployeeUid(request.getUid());
                employeeCard.setDeleteTime(new Date(0));

                if (update) {
                    organizationUserIdCardService.update(employeeCard);
                } else {
                    organizationUserIdCardService.create(employeeCard);
                }
            }
        }else{
            //处理非员工
            //更新非员工信息表
            MbOrgNonEmployeeInfo info = mbOrgNonEmployeeMapper.selectByPrimaryKey(request.getNoEmployeeId());
            if (Objects.nonNull(request.getFirstName()) && Objects.nonNull(request.getLastName())) {
                if (request.getFirstName().equals(info.getLastEnName()) || request.getLastName().equals(info.getFirstEnName())) {
                    needWarn = true;
                }
            }
            info.setName(request.getFullName());
            if(StringUtils.isNotBlank(request.getFirstName()) && StringUtils.isNotBlank(request.getLastName())){
                info.setFirstEnName(request.getFirstName());
                info.setLastEnName(request.getLastName());
            }
            if (DateUtil.isDateDay(request.getBirthday())){
                info.setBirthday(Date.from(ZonedDateTime.of(LocalDate.parse(request.getBirthday(), DateTimeFormatter.ofPattern(DateUtil.DF_YMD)), LocalTime.MIN, ZoneId.of("GMT+8")).toInstant()));
            }
            if (request.getSex() != null) {
                String gender = request.getSex().equals(0) ? "M" : "F";
                info.setGender(gender);
            }
            info.setNationality(request.getNationality());
            info.setEmail(request.getMail());
            info.setMobilePhone(request.getCountryCode() + " " + request.getPhoneNum());
            NameInfoBo nameInfoBo = JsonUtils.parse(JsonUtils.toJsonString(request),NameInfoBo.class);
            if(StrUtils.checkNameInfo(nameInfoBo)){
                info.setNameInfo(JsonUtils.toJsonString(nameInfoBo));
            }
            mbOrgNonEmployeeMapper.updateByPrimaryKeySelective(info);

            //更新出行人新鲜度表
            MbFreshPassenger mbFreshPassenger = new MbFreshPassenger();
            mbFreshPassenger.setNonEmployeeUid(Long.valueOf(request.getNoEmployeeId()));
            mbFreshPassenger.setName(request.getFullName());
            mbFreshPassenger.setEnName(request.getSurname()+ "/" + request.getGivenname() );
            freshPassengerService.updateByNonEmployeeId(mbFreshPassenger);

            //更新证件信息表
            if (Objects.nonNull(request.getCardType())) {
                MbOrgUserIdcard nonEmployeeCard = organizationUserIdCardService.findByNonEmployeeUidAndType(Long.valueOf(request.getNoEmployeeId()), request.getCardType());
                boolean update = true;
                if (Objects.isNull(nonEmployeeCard)) {
                    nonEmployeeCard = new MbOrgUserIdcard();
                    update = false;
                }
                convertCardInfo(nonEmployeeCard, request);
                nonEmployeeCard.setNonEmployeeId(Long.valueOf(request.getNoEmployeeId()));
                nonEmployeeCard.setDeleteTime(new Date(0));

                if (update) {
                    organizationUserIdCardService.update(nonEmployeeCard);
                } else {
                    organizationUserIdCardService.create(nonEmployeeCard);
                }
            }
        }

        if (needWarn){
            MbPassportWarnInfo warnInfo = new MbPassportWarnInfo();
            warnInfo.setCnName(request.getFullName());
            warnInfo.setEnName(request.getFirstName() + "/" + request.getLastName());
            warnInfo.setWarnType(NAME_MATCH_WARN);
            organizationUserFfpService.insertWarnInfo(warnInfo);
        }

        // 更新常旅客信息
        updateRelationPassengerInfo(request, baseUserInfo);

        return JSONResult.success(true);
    }

    private void updateRelationPassengerInfo(PassengerModifyRequest request, BaseUserInfo baseUserInfo) {
        //查询已存在的所有常旅客信息
        List<MbFreshPassengerRelation> exitedList = freshPassengerRelationService.selectByUid(baseUserInfo.getUid());
        Map<String, MbFreshPassengerRelation> exitedMap = null;
        if (!CollectionUtils.isEmpty(exitedList)) {
            exitedMap = exitedList.stream().collect(Collectors.toMap(MbFreshPassengerRelation::getFreshUid, x -> x, (k1, k2) -> k1));
        }
        String freshUid = ApplyTripEmployeeEnum.EXTERNAL_EMPLOYEE.getCode().equals(request.getEmployeeType()) ? request.getNoEmployeeId() : request.getUid();
        // 表中不存在
        if (Objects.isNull(exitedMap) || Objects.isNull(exitedMap.get(freshUid))){
            if (Objects.nonNull(request.getRelationFlag()) && request.getRelationFlag()){
                MbFreshPassengerRelation freshPassengerRelation = new MbFreshPassengerRelation();
                Date date = new Date();
                freshPassengerRelation.setDatachangeCreatetime(date);
                freshPassengerRelation.setDatachangeLasttime(date);
                freshPassengerRelation.setIsDeleted(false);
                freshPassengerRelation.setUid(baseUserInfo.getUid());
                freshPassengerRelation.setFreshTime(date);
                freshPassengerRelation.setEmployeeFlag(ApplyTripEmployeeEnum.EXTERNAL_EMPLOYEE.getCode().equals(request.getEmployeeType()) ? 0 : 1);
                freshPassengerRelation.setFreshUid(freshUid);
                mbFreshPassengerRelationMapper.insertSelective(freshPassengerRelation);
            }
        } else {
            // 表中存在
            MbFreshPassengerRelation relation = exitedMap.get(freshUid);
            Date date = new Date();
            relation.setIsDeleted(!request.getRelationFlag());
            relation.setFreshTime(date);
            relation.setEmployeeFlag(ApplyTripEmployeeEnum.EXTERNAL_EMPLOYEE.getCode().equals(request.getEmployeeType()) ? 0 : 1);
            mbFreshPassengerRelationMapper.updateByPrimaryKeySelective(relation);
        }
    }

    @Override
    public boolean nameRepeatQuery(NameRepeatQueryRequest request) {
        if (Objects.isNull(request.getFullName())){
            throw new CorpBusinessException(OrganizationResponseCodeEnum.NAME_IS_NULL);
        }
        return mbOrgEmployeeLoader.findRepeatName(request.getFullName()) || mbOrgNonEmployeeLoader.findRepeatName(request.getFullName());
    }

    public void convertCardInfo(MbOrgUserIdcard card, PassengerModifyRequest request){
        card.setCardNo(request.getCardId());
        card.setCardType(request.getCardType());
        if (StrUtil.isNotBlank(request.getValidDate())){
            card.setTimeLimit(DateUtil.stringToDate(request.getValidDate(), DateUtil.DF_YMD));
        }
        card.setPlaceOfIssue(request.getPlaceOfIssue());
    }

    @Override
    public QueryOrgInfoWithPermissionResponse queryOrgIdWithPermission(QueryOrgInfoWithPermissionRequest request) {
        QueryOrgInfoWithPermissionResponse response = new QueryOrgInfoWithPermissionResponse();

        // 获取当前登录用户权限下所有orgId
        BaseUserInfo userInfo = UserInfoContext.getContextParams(BaseUserInfo.class);

        Set<String> dataPermissionSet = queryOrgIdWithPermission(userInfo);
        log.info("当前登录用户权限下可查询orgId为：" + JsonUtils.toJsonString(dataPermissionSet));

        if (CollectionUtils.isEmpty(dataPermissionSet)) {
            return response;
        }

        IPage<MbOrgInfo> pageInfo;
        if (StringUtils.isBlank(request.getQueryKey())) {
            pageInfo = PageContext.startPage(request.getPageInfo().getPageNum(),
                request.getPageInfo().getPageSize());
            mbOrgInfoMapper.selectOrgInfoByOrgTypeAndOrgId(dataPermissionSet, request.getQueryOrgType());
        } else {
            List<Long> idList =
                mbOrgInfoMapper.selectOrgInfoByOrgTypeAndOrgId(dataPermissionSet, request.getQueryOrgType()).stream()
                    .filter(orgInfo -> StringUtils.contains(orgInfo.getName(), request.getQueryKey())
                        || StringUtils.contains(orgInfo.getOrgId(), request.getQueryKey()))
                    .map(MbOrgInfo::getId).collect(Collectors.toList());

            if(CollectionUtils.isEmpty(idList)){
                return response;
            }
            pageInfo = PageContext.startPage(request.getPageInfo().getPageNum(),
                request.getPageInfo().getPageSize());
            Example example = new Example(MbOrgInfo.class);
            example.createCriteria().andIn("id", idList);
            mbOrgInfoMapper.selectByExample(example);
        }

        List<OrgInfoWithPermission> result = pageInfo.getRecords().stream()
            .map(org -> OrgInfoWithPermission.builder().orgId(org.getOrgId()).orgName(org.getName())
                .orgType(org.getOrgType()).build())
            .collect(Collectors.toList());
        PageInfoResponse page = new PageInfoResponse();
        page.setPageNum((int)pageInfo.getCurrent());
        page.setPageSize((int)pageInfo.getSize());
        page.setCount((int)pageInfo.getTotal());
        page.setTotalPage((int)pageInfo.getPages());

        response.setPageInfo(page);
        response.setList(result);

        return response;
    }

    /**
     * 查询当前用户下，其能拥有的公司信息
     * @param userInfo
     * @return
     */
    private Set<String> queryOrgIdWithPermission(BaseUserInfo userInfo) {

        // 如果是portal用户，走这个
        if (PORTAL_SOURCE.equals(userInfo.getSource())) {
            return supplierCompanyService.querySupplierCompanyBySupplierCode(userInfo.getSupplierCode()).stream()
                .map(SupplierCompanyDto::getCompanyCode).collect(Collectors.toSet());
        } else if (Boolean.TRUE.equals(userInfo.getBgUser())) {
            // 判断是否是admin用户，如果是，则返回全量数据
            return mbOrgInfoMapper.listAll().stream().map(MbOrgInfo::getOrgId).collect(Collectors.toSet());

        } else {
            // 当前登录用户权限下所有orgId
            return Optional.ofNullable(DataPermissionsContext.getRoleAllDataPermissions())
                .map(ResourceInfo::getDeptInfos).orElse(new ArrayList<>()).stream().map(ResourceInfo.DeptInfo::getOrgId)
                .collect(Collectors.toSet());
        }
    }

    @Override
    public List<OrgInfoVo> findAllByBusinessCodeList(List<String> businessCode) {
        // 查询组织结构信息
        List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listByBusinessCode(businessCode);
        if (CollectionUtils.isNotEmpty(mbOrgInfoList)) {
            ArrayList<OrgInfoVo> list = Lists.newArrayList();
            mbOrgInfoList.forEach(o -> {
                OrgInfoVo orgInfoVo = new OrgInfoVo();
                orgInfoVo.setOrgId(o.getOrgId());
                orgInfoVo.setBusinessCode(o.getBusinessCode());
                list.add(orgInfoVo);
            });
            return list;
        }
        return Collections.emptyList();
    }

    @Override
    public Pair<List<MbOrgEmployeeInfo>,Long> listEmployeeInOrg(ListEmployeeInOrgVO request) {
        Integer pageNum = request.getIndex();
        Integer pageSize = request.getPageSize();
        String orgId = request.getOrgId();
        String condition = request.getStaffInfo();
        Long roleId = request.getRoleId();
        Long jobId = request.getJobId();


        List<MbOrgEmployeeInfo> employeeInfoList = new ArrayList<>();
        ListEmployeeQuery listEmployeeQuery = new ListEmployeeQuery();
        listEmployeeQuery.setPageNum(Objects.nonNull(pageNum) ? pageNum : 1);
        listEmployeeQuery.setPageSize(pageSize);
        Long count = 0L;
        if (StrUtil.isNotBlank(condition) || Objects.nonNull(roleId)) {
            //查询组织
            BaseUserInfo baseUserInfo = userCacheManager.getBaseUserInfo();
            log.info("baseUserInfo: {}", JsonUtils.toJsonString(baseUserInfo));
            boolean ifShowChildCompany = true;
            boolean ifStartWithCompany = true;
            // 查询所有组织结构
            List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listAll();
            // #1.后台用户，查询所有组织结构
            List<GetOrgTreeResponse> getOrgTreeResponses = null;
            if (baseUserInfo.getBgUser()) {
                getOrgTreeResponses = OrganizationUtil.listOrgTree(mbOrgInfoList, null, ifShowChildCompany);
            } else {
                String queryOrgId = null;
                // #2.不是后台用户
                // #2.1需要从最近公司开始展示树
                if (ifStartWithCompany) {
                    queryOrgId = baseUserInfo.getCorpId();
                } else {
                    // #2.2不需要从最近公司开始展示树
                    queryOrgId = baseUserInfo.getOrgId();
                }
                getOrgTreeResponses = OrganizationUtil.listOrgTree(mbOrgInfoList, queryOrgId, ifShowChildCompany);
            }
            List<String> orgIds = new ArrayList<>();
            //查询有权限公司id
            getOrgIds(getOrgTreeResponses, orgIds);
            listEmployeeQuery.setQuery(condition);
            IPage<MbOrgEmployeeInfo> mbOrgEmployeeInfoIPage = userOrgRelationService.listByQueryAndOgrIdsPage(listEmployeeQuery, orgIds, roleId,jobId);
            employeeInfoList = mbOrgEmployeeInfoIPage.getRecords();
            count = mbOrgEmployeeInfoIPage.getTotal();
        } else {
            listEmployeeQuery.setOrgId(orgId);
            IPage<MbOrgEmployeeInfo> mbOrgEmployeeInfoIPage = userOrgRelationService.listByQueryPage(listEmployeeQuery, roleId,jobId);
            employeeInfoList = mbOrgEmployeeInfoIPage.getRecords();
            count = mbOrgEmployeeInfoIPage.getTotal();
        }
        return Pair.of(employeeInfoList,count) ;
    }

    @Override
    public QueryOrgParentCompanyResponse queryOrgParentCompany(QueryOrgParentCompanyRequest request) {
        if (CollectionUtils.isEmpty(request.getOrgIdList())) {
            return new QueryOrgParentCompanyResponse();
        }
        List<MbOrgInfo> orgInfoList = organizationInfoService.listAll();
        List<OrgAndParentCompanyInfoDTO> orgAndParentCompanyInfoList = request.getOrgIdList().stream()
            .map(orgId -> OrganizationUtil.findOrgAndCompanyInfo(orgInfoList, orgId))
            .collect(Collectors.toList());
        QueryOrgParentCompanyResponse response = new QueryOrgParentCompanyResponse();
        response.setOrgAndParentCompanyInfoList(orgAndParentCompanyInfoList);
        response.setAllRelatedParentOrgList(OrganizationUtil.findAllRelatedParentOrgList(
            orgInfoList, request.getOrgIdList()));
        return response;
    }

    private void getOrgIds(List<GetOrgTreeResponse> orgTreeResponses, List<String> orgIds) {
        for (GetOrgTreeResponse orgTreeResponse : orgTreeResponses) {
            orgIds.add(orgTreeResponse.getOrgId());
            if (orgTreeResponse.getChildren() != null && orgTreeResponse.getChildren().size() > 0) {
                getOrgIds(orgTreeResponse.getChildren(), orgIds);
            }
        }
    }

    @Override
    public List<ListOrgTreeByConditionResponse> listOrgTreeByCondition(ListOrgTreeByConditionRequest request, BaseUserInfo baseUserInfo) {
        // 1.1 查询所有组织结果
        List<MbOrgInfo> fullOrgInfoList = this.listAll();
        Map<String, MbOrgInfo> fullOrgInfoMap = fullOrgInfoList.stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, item -> item, (o1, o2) -> o1));

        // 1.2 筛选符合条件的组织结构
        List<MbOrgInfo> mbOrgInfoList =  listOrgInfoByCondition(fullOrgInfoList, request);

        // 1.3 根据数据权限进行过滤
        mbOrgInfoList = filterByRole(mbOrgInfoList, baseUserInfo);

        // 3.将已过滤的所有节点实体转换，并加入list中
        ArrayList<ListOrgTreeByConditionResponse> nodeList = listOrgTreeByConditionListConvert(mbOrgInfoList);
        for (int i = 0; i < nodeList.size(); i++){
            packageOrgDataRecursion(nodeList.get(i), nodeList, fullOrgInfoMap, RECURSION_TIMES);
        }
        // 4.查询每个组织对应的人数
        List<String> orgIdList = nodeList.stream().map(ListOrgTreeByConditionResponse::getOrgId).collect(Collectors.toList());
        Map<String, Map<String, Long>> orgUidMap = mbUserOrgRelationLoader.countUidByOrgIds(orgIdList);
        nodeList.forEach(e ->{
            e.setPersonNum(Optional.ofNullable(orgUidMap.get(e.getOrgId())).map(k -> k.get("uidCount")).map(Long::intValue) .orElse(0));
        });
        return nodeList.stream().filter(e -> e.getLevel() == 1).collect(Collectors.toList());
    }

    private void packageOrgDataRecursion(ListOrgTreeByConditionResponse mbOrgInfo, ArrayList<ListOrgTreeByConditionResponse> nodeList, Map<String, MbOrgInfo> fullOrgInfoMap, int recursionTimes) {
        // 限制最大循环次数
        if (recursionTimes <= 0){
            return;
        }
        // 无上级节点直接返回
        if (mbOrgInfo.getLevel() <= 1 || Objects.isNull(mbOrgInfo.getParentId())){
            return;
        }
        // 查询直接父节点
        MbOrgInfo parentOrgInfo = fullOrgInfoMap.get(mbOrgInfo.getParentId());
        if (Objects.isNull(parentOrgInfo)){
            return;
        }
        // 实体转换
        ListOrgTreeByConditionResponse parentNode = listOrgTreeByConditionConvert(parentOrgInfo);
        // 查询list中是否已存在该父节点
        ListOrgTreeByConditionResponse org = nodeList.stream().filter(e -> e.getOrgId().equals(parentOrgInfo.getOrgId())).findFirst().orElse(null);
        // 该父节点未遍历过则将当前节点挂到父节点上，并加入list中
        if (Objects.isNull(org)){
            ArrayList<ListOrgTreeByConditionResponse> children = new ArrayList<>();
            children.add(mbOrgInfo);
            parentNode.setChildren(children);
            nodeList.add(parentNode);
        } else {
            // 已遍历过则直接将当前节点挂到父节点上，已挂过则跳过
            if (CollectionUtils.isEmpty(org.getChildren())){
                ArrayList<ListOrgTreeByConditionResponse> children = new ArrayList<>();
                children.add(mbOrgInfo);
                org.setChildren(children);
            } else {
                ListOrgTreeByConditionResponse orgInfo = org.getChildren().stream().filter(e -> e.getOrgId().equals(mbOrgInfo.getOrgId())).findFirst().orElse(null);
                if (Objects.isNull(orgInfo)){
                    org.getChildren().add(mbOrgInfo);
                }
            }
        }
        // 处理父节点
        packageOrgDataRecursion(parentNode, nodeList, fullOrgInfoMap,recursionTimes - 1);
    }

    private ArrayList<ListOrgTreeByConditionResponse> listOrgTreeByConditionListConvert(List<MbOrgInfo> mbOrgInfoList) {
        ArrayList<ListOrgTreeByConditionResponse> list = new ArrayList<>();
        if (CollectionUtils.isEmpty(mbOrgInfoList)){
            return list;
        }
        mbOrgInfoList.forEach(e ->{
            list.add(listOrgTreeByConditionConvert(e));
        });
        return list;
    }

    private ListOrgTreeByConditionResponse listOrgTreeByConditionConvert(MbOrgInfo mbOrgInfo) {
        ListOrgTreeByConditionResponse node = new ListOrgTreeByConditionResponse();
        node.setOrgId(mbOrgInfo.getOrgId());
        node.setType(mbOrgInfo.getOrgType());
        node.setLabel(mbOrgInfo.getName());
        node.setBusinessCode(mbOrgInfo.getBusinessCode());
        node.setParentBusinessCode(mbOrgInfo.getParentBusinessCode());
        node.setLevel(mbOrgInfo.getLevel());
        node.setParentId(mbOrgInfo.getParentId());
        node.setValid(mbOrgInfo.getValid());
        return node;
    }

    @Override
    public List<MbOrgInfo> filterByRole(List<MbOrgInfo> mbOrgInfoList, BaseUserInfo baseUserInfo) {
        if (baseUserInfo.getDataPermissionControl()){
            ResourceInfo resourceInfo = manager.getResource(String.valueOf(baseUserInfo.getRoleId()), ResourceInfo.class);
            List<ResourceInfo.DeptInfo> deptInfos = resourceInfo.getDeptInfos();
            mbOrgInfoList = getMbOrgInfoList(mbOrgInfoList, deptInfos);
        }
        return mbOrgInfoList;
    }

    private List<MbOrgInfo> getMbOrgInfoList(List<MbOrgInfo> mbOrgInfoList, List<ResourceInfo.DeptInfo> org) {
        List<MbOrgInfo> mbOrgInfos = new ArrayList<>();
        if (org.stream().allMatch(deptInfo -> !Objects.equals(OrgTypeEnum.D.getCode(), deptInfo.getOrgType()))) {

            for (ResourceInfo.DeptInfo deptInfo : org) {
                Map<String, List<MbOrgInfo>> parentIdMapList = mbOrgInfoList.stream().filter(mbOrgInfo -> StringUtils.isNotBlank(mbOrgInfo.getParentId())).collect(Collectors.groupingBy(MbOrgInfo::getParentId));
                List<String> departmentIds = CollUtil.newArrayList();
                listAllDepartmentIdsByCompanyId(deptInfo.getOrgId(), parentIdMapList, departmentIds);
                List<MbOrgInfo> result = mbOrgInfoList.stream().filter(o -> departmentIds.contains(o.getOrgId()) || Objects.equals(o.getOrgId(), deptInfo.getOrgId())).collect(Collectors.toList());

                mbOrgInfos.addAll(result);
            }
            return mbOrgInfos;
        }
        mbOrgInfos = mbOrgInfoList.stream().filter(x -> org.stream().map(ResourceInfo.DeptInfo::getOrgId).collect(Collectors.toSet()).contains(x.getOrgId())).collect(Collectors.toList());
        return mbOrgInfos.stream().distinct().collect(Collectors.toList());
    }

    private List<MbOrgInfo> listOrgInfoByCondition(List<MbOrgInfo> fullOrgInfoList ,ListOrgTreeByConditionRequest request) {
        if (CollectionUtils.isEmpty(fullOrgInfoList)){
            return fullOrgInfoList;
        }
        if (StringUtils.isNotBlank(request.getLabel())){
            fullOrgInfoList = fullOrgInfoList.stream().filter(e -> e.getName().contains(request.getLabel())).collect(Collectors.toList());
        }
        if (StringUtils.isNotBlank(request.getBusinessCode())){
            fullOrgInfoList = fullOrgInfoList.stream().filter(e -> e.getBusinessCode().contains(request.getBusinessCode())).collect(Collectors.toList());
        }
        if (StringUtils.isNotBlank(request.getType())){
            fullOrgInfoList = fullOrgInfoList.stream().filter(e -> request.getType().equals(e.getOrgType())).collect(Collectors.toList());
        }
        if (StringUtils.isNotBlank(request.getValid())){
            fullOrgInfoList = fullOrgInfoList.stream().filter(e -> request.getValid().equals(e.getValid())).collect(Collectors.toList());
        }
        return fullOrgInfoList;
    }

    private String nameInfoConvert(PassengerModifyRequest request){
        NameInfoVo nameInfoVo = new NameInfoVo();
        nameInfoVo.setFullName(request.getFullName());
        nameInfoVo.setSurname(request.getSurname());
        nameInfoVo.setGivenname(request.getGivenname());
        nameInfoVo.setNationality(request.getNationality());
        return JsonUtils.toJsonString(nameInfoVo);
    }
}
